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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步