码迷,mamicode.com
首页 > 其他好文 > 详细

宽度优先搜索

时间:2014-09-30 13:47:29      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

给定大小为N*M的迷宫,求出起点到终点的最小步数。

输入

10 10

#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

输出

22

 1 #include <iostream>
 2 #include <fstream>
 3 #include <queue>
 4 using namespace std;
 5 
 6 #define MAX_N 100
 7 #define MAX_M 100
 8 
 9 const int INF = 100000000;
10 
11 //pair<int,int>表示坐标状态
12 typedef pair<int, int> P;
13 
14 //输入
15 char maze[MAX_N][MAX_M];  //表示迷宫字符串数组
16 int N, M;
17 int sx, sy;   //起点坐标
18 int gx, gy;   //终点坐标
19 
20 int d[MAX_N][MAX_M];    //到各个位置的作短距离
21 
22 //4个方向移动的向量
23 int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
24 
25 
26 //求从(sx, sy)到(gx, gy)的最短距离
27 //如无法到达,则是INF
28 int BFS()
29 {
30     queue<P> que;
31     //把所有位置的距离都初始化为INF
32     for (int i = 0; i < N; i++)
33         for (int j = 0; j < M; j++)
34             d[i][j] = INF;
35     //将起点加入队列,并把距离设为0
36     que.push(P(sx, sy));
37     d[sx][sy] = 0;
38 
39     //不断循环直到队列长度为0
40     while (que.size())
41     {
42         P p = que.front(); que.pop();
43 
44         if (p.first == gx && p.second == gy)
45             break;
46 
47         for (int i = 0; i < 4; i++)
48         {
49             int nx = p.first + dx[i], ny = p.second + dy[i];
50             
51             if (0 <= nx && nx < N && 0 <= ny && ny < M && maze[nx][ny] != # && d[nx][ny] == INF)
52             {
53                 que.push(P(nx, ny));
54                 d[nx][ny] = d[p.first][p.second] + 1;
55             }
56         }
57     }
58     return d[gx][gy];
59 }
60 
61 int main()
62 {
63     ifstream cin("input");
64 
65     cin >> N >> M;
66 
67     for (int i = 0; i < N; i++)
68         for (int j = 0; j < M; j++)
69         {
70             cin >> maze[i][j];
71             if (maze[i][j] == S)
72             {
73                 sx = i;
74                 sy = j;
75             }
76             else if (maze[i][j] == G)
77             {
78                 gx = i;
79                 gy = j;
80             }
81         }
82 
83     cout << BFS() << endl;
84 
85     return 0;
86 }

 

宽度优先搜索

标签:style   blog   color   io   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/bournet/p/4001620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!