迷宫问题——最短路

一、题目(POJ 3984)

给出一个只有0和1组成的5x5的矩阵表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

二、解题思路

迷宫问题中的最短路多用BFS,由于要输出最短路,一般可以在更新时保存前驱节点,这里使用DFS从终点寻找距离一次减一的节点,直到到达起点。

三、代码实现

  1 #include<stdio.h>
  2 #include<iostream>
  3 #include<queue>
  4 #include<stack>
  5 #include<stdbool.h>
  6 using namespace std;
  7 
  8 typedef pair<int, int> P;
  9 const int INF = 1000000;
 10 const int max_n = 100 + 10;
 11 const int max_m = 100 + 10;
 12 int n, m;
 13 int sx, sy, ex, ey;
 14 int dis[max_n][max_m];
 15 int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
 16 int maze[max_n][max_m + 1];
 17 bool vis[max_n][max_m + 1];
 18 stack<P>s;
 19                 
 20 int bfs()
 21 {
 22     queue<P>que;
 23     for (int i = 0; i < n; i++)
 24         for (int j = 0; j < m; j++)
 25             dis[i][j] = INF;
 26     dis[sx][sy] = 0;
 27     que.push(make_pair(sx, sy));
 28     while (!que.empty())
 29     {
 30         P p = que.front();
 31         que.pop();
 32         int xx = p.first; int yy = p.second;
 33         if (xx == ex && yy == ey)  break;
 34 
 35         for (int i = 0; i < 4; i++)
 36         {
 37             int nx = xx + dx[i]; int ny = yy + dy[i];
 38             if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] == 0 && dis[nx][ny] == INF)
 39             {
 40                 que.push(make_pair(nx, ny));
 41                 dis[nx][ny] = dis[xx][yy] + 1;
 42             }
 43         }
 44     }
 45     return dis[ex][ey];
 46 }
 47 
 48 void dfs(int x,int y)
 49 {
 50     
 51     if (x == ex && y == ey)
 52         s.push(make_pair(x, y));
 53 
 54     if (x == sx && y == sy)
 55     {
 56         while (!s.empty())
 57         {
 58             P tmp = s.top();
 59             s.pop();
 60             printf("(%d, %d)
", tmp.first, tmp.second);
 61         }
 62         return;
 63     }
 64     else
 65     {
 66         P tmp2 = s.top();
 67         //s.pop();
 68         int xx = tmp2.first; int yy = tmp2.second;
 69         for (int i = 0; i < 4; i++)
 70         {
 71             int nx = xx + dx[i]; int ny = yy + dy[i];
 72             if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] == 0)
 73                 if (dis[nx][ny] == dis[xx][yy] - 1)
 74                 {
 75                     vis[nx][ny] = true;
 76                     s.push(make_pair(nx, ny));
 77                     dfs(nx, ny);
 78                         
 79                     vis[nx][ny] = false;
 80                     if(!s.empty())  s.pop();
 81                 }
 82         }
 83     }
 84     return;
 85 }
 86 void slove()
 87 {
 88     int res = bfs();
 89     dfs(ex,ey);
 90 }
 91 
 92 int main()
 93 {
 94     n = 5; m = 5;
 95     for (int i = 0; i < n; i++)
 96         for (int j = 0; j < m; j++)
 97             cin >> maze[i][j];
 98 
 99     sx = 0; sy = 0;
100     ex = 4; ey = 4;
101     slove();
102     return 0;
103 }
原文地址:https://www.cnblogs.com/lfri/p/9655815.html