breadth-first-search - 广度优先搜索简单改进
问题描述
在大多数资源中,BFS 的实现是这样的(这是极客实现极客的极客):
void findpaths(vector<vector<int> >&g, int src,
int dst, int v)
{
// create a queue which stores
// the paths
queue<vector<int> > q;
// path vector to store the current path
vector<int> path;
path.push_back(src);
q.push(path);
while (!q.empty()) {
path = q.front();
q.pop();
int last = path[path.size() - 1];
// if last vertex is the desired destination
// then print the path
if (last == dst)
printpath(path);
// traverse to all the nodes connected to
// current vertex and push new path to queue
for (int i = 0; i < g[last].size(); i++) {
if (isNotVisited(g[last][i], path)) {
vector<int> newpath(path);
newpath.push_back(g[last][i]);
q.push(newpath);
}
}
}
上面的实现建议我们首先将邻居添加到队列中,然后我们将检查它是否是我们的目的地。
但是我们可以在将邻居添加到队列时简单地检查邻居是否是目的地(而不是在轮到该节点时检查它)虽然这是一个非常小的改进,但比上一个要好。那么为什么大家都用之前的方法来实现BFS呢?
解决方案
推荐阅读
- ruby - 按特定键对 ruby 哈希进行排序
- performance - OCaml 和内存中的自定义类型
- xamarin.forms - Xamarin Forms Android 搜索栏删除下划线
- python - 在 Python 上安装 Cantera 的问题
- typescript - 尝试将扩展运算符与 TypeScript 和 Object.assign 一起使用
- r - 为数据框中的每一行标识具有非零值的第一列
- events - Maximo:在更新相关表时使用脚本更新工单
- excel - Next without For Error, If Else 语句
- google-chrome - Chrome window.open 显示失败 - 网络错误
- c# - 更改场景时如何使用 UnitySingleton 保存 int 值?