BFS 打印最短路径
BFS print shortest path
我正在尝试实现BFS算法以在统一加权图上找到最短路径。下面的代码是从这里直接实现BFS:https://www.redblobgames.com/pathfinding/a-star/introduction.html
void print_path(vector<vector<int>> & gr, int xf, int yf, int xt, int yt)
{
/* Cell neighbours */
const vector<pair<int,int>> nbr {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
/* route breadcrumbs */
map<pair<int,int>,pair<int,int>> route;
queue<pair<int,int>> q;
/* Represent each node as a pair<int,int> */
pair<int,int> start = {xf, yf};
pair<int,int> end = {xt, yt};
/* NULL node */
route[start] = {-1, -1};
q.push(start);
while (!q.empty()) {
auto current = q.front();
q.pop();
if (current == end) break;
/* Iterate through all possible neighbours */
for (const auto & n : nbr) {
/* pair<int,int> operator+ overloaded */
auto next = current + n;
/* Can move to the next node and it is not yet in the route */
if (can_move_to(next, gr) && route.find(next) == route.end()) {
q.push(next);
route[next] = current;
}
}
}
/* Trace back the shortest path */
while (route[end] != pair<int,int>(-1, -1)) {
cout << end.first << ';' << end.second << endl;
end = route[end];
}
/* Print the starting node */
cout << end.first << ';' << end.second << endl;
}
也许我错过了一些东西,但代码没有产生最短的路径(我不明白为什么要这样做(。此功能沿直角边打印路径,而不是围绕斜边"摆动"。
好吧,在纸和铅笔的帮助下,解决方案非常明显(但我无法证明这一点(。如果我改变每个"层"的邻居迭代顺序,那么对角线路径将改变它的方向,从而产生有效的(最短的?(路径。话虽如此,内部 nbr 循环应该看起来像这样:
if ((current.first + current.second) & 1) {
/* Odd layers */
for (auto it = nbr.begin(); it != nbr.end(); it++) {
auto next = current + *it;
if (can_move_to(next, gr) && route.find(next) == route.end()) {
q.push(next);
route[next] = current;
}
}
}
else {
/* Even layers */
for (auto it = nbr.rbegin(); it != nbr.rend(); it++) {
auto next = current + *it;
if (can_move_to(next, gr) && route.find(next) == route.end()) {
q.push(next);
route[next] = current;
}
}
}
相关文章:
- 内存效率表示最短路径的方法?
- 用于查找网格中最短路径的算法
- 查找最短路径算法
- BFS 打印最短路径
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 使用C++具有两个数字的最短路径算法.(C++)
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 如何使用贝尔曼-福特算法返回所有具有捆绑重量的最短路径?
- 使用优先级队列查找所有与 Dijkstra 相同的最短路径
- 尝试在图形中查找最短路径时的无限循环
- C++计算有向图中的最短路径
- 使用BFS存储和打印最短路径
- 如何制作由原始图形的最短路径边组成的新图形
- 有没有一种方法可以使用弗洛伊德-沃歇尔算法给出最短路径,其中存在负权重循环而不允许重叠边缘?
- 如何使用递归来查找和打印从A点到B点的多条最短路径?(C++)
- 矩阵遍历打印所有和最短路径 - 无限循环
- 使用改进的弗洛伊德战争打印最短路径黑白给定节点
- 最短路径,无左转弯,打印路径
- 如何打印图中两个顶点之间的最短路径?