FZU 2285 迷宫寻宝

思路:

bfs求最短路径。

 

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<queue>
 4 #include<cstring>
 5 #define maxn 105
 6 using namespace std;
 7 int sx, sy, ex, ey;
 8 char map[1010][1010];
 9 char vis[1010][1010];
10 int dic[4][2] = { { -1,0 },{ 0,-1 },{ 1,0 },{ 0,1 } };//4个方向 
11 int res;
12 struct node {
13     int x, y, step;
14 };
15 int n;
16 bool check(int x, int y)
17 {
18     if (x >= 0 && x < n&&y >= 0 && y < n&&map[x][y] != '#'&&vis[x][y] !=1)
19         return true;
20     //printf("x=%d y=%d c=%c\n", x, y,map[x][y]);
21     return false;
22 }
23 
24 void bfs()
25 {
26     queue<node> q;
27     node a;
28     node next;
29     a.x = sx;
30     a.y = sy;
31     a.step = 0;
32     vis[a.x][a.y] = 1;
33     q.push(a);
34     while (!q.empty())
35     {
36         a = q.front();
37         q.pop();
38         for (int i = 0; i<4; i++)
39         {
40             next = a;
41             next.x += dic[i][0];
42             next.y += dic[i][1];
43             next.step = a.step + 1;
44             if (next.x == ex&&next.y == ey)//找到出口 
45             {
46                 res = next.step;
47             //    printf("res=%d\n", res);
48                 return;
49             }
50             if (check(next.x, next.y))//检查合法性 
51             {
52                 vis[next.x][next.y] = 1;
53                 //printf("vis[%d][%d]=1\n", next.x, next.y);
54                 q.push(next);
55             }
56         }
57     }
58     res = -1;
59 }
60 int main()
61 {
62     while (scanf("%d", &n) == 1)
63     {
64         for (int i = 0; i<n; i++)
65             scanf("%s", &map[i]);
66         memset(vis, 0, sizeof(vis));
67         //for (int i = 0; i < n; i++)
68             //printf("%s\n", map[i]);
69         for (int i = 0; i<n; i++)
70         {
71             for (int j = 0; j<n; j++)
72             {
73                 if (map[i][j] == 'S')
74                 {
75                     sx = i;
76                     sy = j;
77                 }
78                 if (map[i][j] == 'E')
79                 {
80                     ex = i;
81                     ey = j;
82                 }
83             }
84         }
85         //printf("sx=%d sy=%d ex=%d ey=%d\n", sx, sy, ex, ey);
86         bfs();
87         printf("%d\n", res);
88     }
89     return 0;
90 }

 

posted @ 2019-03-22 21:53  付玬熙  阅读(196)  评论(0编辑  收藏  举报