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

时间:2016-12-08 01:52:58

标签: c++ matrix breadth-first-search

我之前看过类似的问题,但我还没有找到适合我的解决方案。我有一个初始化为0的2D矢量矩阵。 'S'字符表示起点,'E'字符表示出口点,'X'字符表示障碍物。对象是在避开X的同时将S移动到E.我理解BFS可以使用图形,但是我不确定如何用矩阵实现它。

以下是我在带有图表的程序中使用的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

谢谢!

1 个答案:

答案 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

你的回答将是[i] [j]。

您可以轻松验证是否可以通过一些重要值来初始化所有可能的距离。

当您从禁用的单元格返回时,您可以保证到达终点的方式不会来自它。