迷宫的最短路径 代码(C++)

迷宫的最短路径 代码(C++)


本文地址: http://blog.csdn.net/caroline_wendy


题目: 给定一个大小为N*M的迷宫. 迷宫由通道和墙壁组成, 每一步可以向邻接的上下左右四格的通道移动.

请求出从起点到终点所需的最小步数. 请注意, 本题假定从起点一定可以移动到终点.


使用宽度优先搜索算法(DFS), 依次遍历迷宫的四个方向, 当有可以走且未走过的方向时, 移动并且步数加一.

时间复杂度取决于迷宫的状态数, O(4*M*N)=O(M*N).


代码:

[cpp]  view plain copy
  1. /* 
  2.  * main.cpp 
  3.  * 
  4.  *  Created on: 2014.7.17 
  5.  *      Author: spike 
  6.  */  
  7.   
  8. /*eclipse cdt, gcc 4.8.1*/  
  9.   
  10. #include   
  11. #include   
  12.   
  13. #include   
  14. #include   
  15.   
  16. using namespace std;  
  17.   
  18. class Program {  
  19.     static const int MAX_N=20, MAX_M=20;  
  20.     const int INF = INT_MAX>>2;  
  21.     typedef pair<intint> P;  
  22.   
  23.     char maze[MAX_N][MAX_M+1] = {  
  24.             "#S######.#",  
  25.             "......#..#",  
  26.             ".#.##.##.#",  
  27.             ".#........",  
  28.             "##.##.####",  
  29.             "....#....#",  
  30.             ".#######.#",  
  31.             "....#.....",  
  32.             ".####.###.",  
  33.             "....#...G#"  
  34.     };  
  35.     int N = 10, M = 10;  
  36.     int sx=0, sy=1; //起点坐标  
  37.     int gx=9, gy=8; //重点坐标  
  38.   
  39.     int d[MAX_N][MAX_M];  
  40.   
  41.     int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; //四个方向移动的坐标  
  42.   
  43.     int bfs() {  
  44.         queue

     que;  

  45.         for (int i=0; i
  46.             for (int j=0; j
  47.                 d[i][j] = INF;  
  48.   
  49.         que.push(P(sx, sy));  
  50.         d[sx][sy] = 0;  
  51.   
  52.         while (que.size()) {  
  53.             P p = que.front(); que.pop();  
  54.             if (p.first == gx && p.second == gy) break;  
  55.             for (int i=0; i<4; i++) {  
  56.                 int nx = p.first + dx[i], ny = p.second + dy[i];  
  57.                 if (0<=nx&&nx'#'&&d[nx][ny]==INF) {  
  58.                     que.push(P(nx,ny));  
  59.                     d[nx][ny]=d[p.first][p.second]+1;  
  60.                 }  
  61.             }  
  62.         }  
  63.         return d[gx][gy];  
  64.     }  
  65. public:  
  66.     void solve() {  
  67.         int res = bfs();  
  68.         printf("result = %d\n", res);  
  69.     }  
  70. };  
  71.   
  72.   
  73. int main(void)  
  74. {  
  75.     Program P;  
  76.     P.solve();  
  77.     return 0;  
  78. }  

输出:

[plain]  view plain copy
  1. result = 22  

你可能感兴趣的:(c/c++学习笔记)