题目描述
给定一个迷宫,找到从开始到目标的最短路径。
输入
Input consists serveral test cases.
First line of the input contains number of test case T.
For each test case the first line contains two integers N , M ( 1 <= N, M <= 100 ).
Each of the following N lines contain M characters. Each character means a cell of the map.
Here is the definition for chracter.
Constraint:
- For a character in the map:
- 'S' : start cell
- 'E' : goal cell
- '-' : empty cell
- '#' : obstacle cell
- no two start cell exists.
- no two goal cell exists.
输出
For each test case print one line containing shortest path. If there exists no path from start to goal, print -1.
样例输入
1 5 5 S-### ----- ##--- E#--- ---##样例输出
9
#include<stdio.h> #include<string.h> #include<math.h> #include<malloc.h> #define INF 0x3f3f3f3f #define MAX(x,y) (x>y?x:y) #define MIN(x,y) (x>y?y:x) #define M 100 int dir[][2] = { {1,0},{0,-1},{0,1},{-1,0} }; char a[M][M]; int vis[M][M]; int xa, ya,xb,yb; int m, k; int flag = 1; struct node { int x; int y; int step; }q[M*M]; void bfs(int xb, int yb,int xa,int ya) { int head = 1, tail = 1; q[tail].x = xb; q[tail].y = yb; q[tail].step = 0; vis[xb][yb] = 1; tail++; while (head < tail) { int x = q[head].x; int y = q[head].y; int step = q[head].step; if (x == xa && y == ya) { flag = 0; printf("%d\n", step); break; } for (int i = 0; i < 4; i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if (nx >= 0 && nx < m && ny >= 0 && ny < k && a[nx][ny] == '-' && vis[nx][ny] == 0) { vis[nx][ny] = 1; q[tail].x = nx; q[tail].y = ny; q[tail].step = step + 1; tail++; } } head++; } if (flag == 1) { printf("-1\n"); } } int main() { int n; scanf("%d", &n); while (n--) { flag = 1; memset(vis, 0, sizeof(vis)); scanf("%d%d", &m, &k); for (int i = 0; i < m; i++) { scanf("%s", a[i]); } for (int i = 0; i < m; i++) { for (int j = 0; j < k; j++) { if (a[i][j] == 'S') { xb = i; yb = j; } if (a[i][j] == 'E') { xa = i; ya = j; a[i][j] = '-'; } } } bfs(xb, yb, xa, ya); } return 0; }
SWUST OJ4:迷宫问题
最新推荐文章于 2022-09-02 22:37:11 发布