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 }

 

转载于:https://www.cnblogs.com/fudanxi/p/10581237.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值