如何在2D矩阵中找到最短路径,以免避免某些坐标?C
How can I find the shortest path in a 2D matrix, so that it avoids certain coordinates? C++
我以前看过与此问题相似的问题,但是我尚未找到对我有用的解决方案。我有一个用0初始化的2D矢量矩阵。一个" s"字符表示起点," e"字符表示出口点,而" x"字符表示障碍。该对象是在避免X时移动s。
这是我在带有图形的程序中使用的BFS搜索:
void Graph::BFS(int s, int d)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
int trail[V];
for(int i = 0; i < V; i++){
visited[i] = false;
trail[i] = -1;
}
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
if(s == d){
break;
}
else
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
trail[*i] = s;
}
}
}
int x = d;
while(x != -1){
cout<<x<<endl;
x = trail[x];
}
}
这打印出路径。有没有办法将其修改以适用于矩阵?
*注意:我想在适当的时候纳入对角线的路径。
Example Matrix:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 S 0 0 0 0 X 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 X 0 0 0 0 0
0 0 0 0 0 0 0 X E 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
谢谢!
您可以运行BFS。
对于每个单元格,请立即将其标记,然后转到所有可能的方向(未标记),并在它们与起始单元之间设置正确的距离(由于它是BFS,很容易计算)。
每当您到达您无法通过的单元格时,只需从中返回。
伪代码可能是:
void BFS(int i, int j, int currentDistance){
mark[i][j] = true
dist[i][j] = currentDistance
if this cell is forbidden, return;
let S be the set with all possible pairs (x,y) possible to go
for each (x,y) in S:
if( !mark[x][y] ) BFS(x, y, currentDistance + 1)
end
您的答案将为dist [i] [j]。
您可以轻松地验证是否可以到达那里,以一定的价值初始化所有可能的距离。
当您从禁忌单元返回时,您保证通往终点的方式不会来自它。
相关文章:
- 内存效率表示最短路径的方法?
- 用于查找网格中最短路径的算法
- 查找最短路径算法
- BFS 打印最短路径
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 使用C++具有两个数字的最短路径算法.(C++)
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 如何使用贝尔曼-福特算法返回所有具有捆绑重量的最短路径?
- 使用优先级队列查找所有与 Dijkstra 相同的最短路径
- 尝试在图形中查找最短路径时的无限循环
- C++计算有向图中的最短路径
- 使用BFS存储和打印最短路径
- 如何制作由原始图形的最短路径边组成的新图形
- 有没有一种方法可以使用弗洛伊德-沃歇尔算法给出最短路径,其中存在负权重循环而不允许重叠边缘?
- 加权图的开始和结束的最短路径
- 使 c++11 Dijkstra 实现返回最短路径
- 弗洛伊德最短路径算法C++
- 如何在2D矩阵中找到最短路径,以免避免某些坐标?C
- 用X-Y坐标表示的点之间的最短路径距离