使用 BFS 查找最短路径
Using BFS to find the shortest path
正如小人物所说,我试图找到一个单位移动到近东控制点的最短路径(就像它是宝藏或其他东西一样)。我试图使用 BFS 找到这条路径,但它没有给出最短的路径。例如:
如果我们有这样的东西(其中 X 是起始位置,K 是一个控制点)
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · X · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · K · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
我的代码给出了以下路径:
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · - - - · · · · · · ·
· · | X | · · · · · · ·
· · | | - · · · · · · ·
· · | · · · · · · · · ·
· · | · · · · · · · · ·
· · · | · · · · · · · ·
· · · | - K · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
但我不明白为什么它会给我这些额外的动作。有人能说出我做错了什么?
typedef pair<int,int> Coord;
typedef vector< vector<bool> > VIS;
typedef vector<vector< Coord> > Prev;
const int X[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
const int Y[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
list<Coord> BFS2(int x, int y, VIS& visited, Prev& p) {
queue<Coord> Q;
Coord in;
in.first = x; in.second = y;
Q.push(in);
bool found = false;
Coord actual;
while( not Q.empty() and not found){
actual = Q.front();
Q.pop();
int post = who_post(actual.first, actual.second); //It tells if we're in a control point or not(0 == if we are not in the C.point)
if(post != 0){
found = true;
}
else {
visited[actual.first][actual.second]=true;
for( int i = 0; i < 8; i++){
int nx = X[i] + actual.first;
int ny = Y[i] + actual.second;
//The maze is 60x60, but the borders are all mountains, so we can't access there
if(nx>=1 and nx<59 and ny>=1 and ny<59 and not visited[nx][ny]){
Coord next;
next.first = nx; next.second = ny;
Q.push(next);
p[nx][ny] = actual;
}
}
}
}
list<Coord> res;
while(actual != in){
res.push_back(actual);
actual = p[actual.first][actual.second];
}
res.reverse();
return res;
}
我认为
这与你如何计算我们之前的矩阵有关。具体如下代码
if(nx>=1 and nx<59 and ny>=1 and ny<59 and not visited[nx][ny]){
...
p[nx][ny] = actual;
}
每当遇到具有当前正在探索的节点的未邀请节点时,都会更新上一个矩阵。但是,请考虑开始时会发生什么。 您将围绕起始位置对每个点进行排队,并将每个节点的上一个矩阵标记为起点。现在,您将探索其他节点。除了起点之外,它的每个邻居都将排队,因为他们都没有被访问过。上一个矩阵中的某些整体将被覆盖。这就是为什么你的路径没有意义。
相关文章:
- 内存效率表示最短路径的方法?
- 用于查找网格中最短路径的算法
- 查找最短路径算法
- BFS 打印最短路径
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 使用C++具有两个数字的最短路径算法.(C++)
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 如何使用贝尔曼-福特算法返回所有具有捆绑重量的最短路径?
- 使用优先级队列查找所有与 Dijkstra 相同的最短路径
- 尝试在图形中查找最短路径时的无限循环
- C++计算有向图中的最短路径
- 如何使用递归来查找和打印从A点到B点的多条最短路径?(C++)
- 在有向图中查找第二条最短路径
- 带地图的 GUI C++最短路径查找器
- 使用 BFS 查找 2 个节点之间的最短路径
- 使用具有指定最大距离的 Boost Dijkstra 查找最短路径
- 使用 BFS 查找最短路径
- 运行 BFS 以查找从图形底部到顶部的最短路径
- 使用 Dijkstra 和最小堆 c++ 查找节点之间的最短路径