如何在2D矩阵中找到最短路径,以免避免某些坐标?C

How can I find the shortest path in a 2D matrix, so that it avoids certain coordinates? C++

本文关键字:坐标 最短路径 2D      更新时间:2023-10-16

我以前看过与此问题相似的问题,但是我尚未找到对我有用的解决方案。我有一个用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]。

您可以轻松地验证是否可以到达那里,以一定的价值初始化所有可能的距离。

当您从禁忌单元返回时,您保证通往终点的方式不会来自它。