迷宫的最短路径 代码(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 <stdio.h>  
  11. #include <limits.h>  
  12.   
  13. #include <utility>  
  14. #include <queue>  
  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<P> que;  
  45.         for (int i=0; i<N; ++i)  
  46.             for (int j=0; j<M; ++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<N&&0<=ny&&ny<M&&maze[nx][ny]!='#'&&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  
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值