地图很小,50×50,所以普通的BFS就行了;
1WA:地图用%s读取时,读入的是字符0,在判断是否有路径时和数值0比较。
1 # include <stdio.h> 2 # include <string.h> 3 4 typedef struct {short x, y;}queue; 5 6 const short dir[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}}; 7 8 int r, c, sr, sc, er, ec; 9 char m[55][55], v[55][55], d[55][55]; 10 queue Q[55*55]; 11 12 void read(void) 13 { 14 int i; 15 16 scanf("%d%d%d%d%d%d", &r, &c, &sr, &sc, &er, &ec); 17 for (i = 1; i <= r; ++i) 18 scanf("%s", m[i]+1); 19 20 /* 设置边界 */ 21 for (i = 0; i <= c; ++i) 22 { 23 m[0][i] = 1; 24 m[r+1][i+1] = 1; 25 } 26 for (i = 0; i <= r; ++i) 27 { 28 m[i][c+1] = 1; 29 m[i+1][0] = 1; 30 } 31 } 32 33 void solve(void) 34 { 35 int front, rear, ans, i; 36 queue cur, nst; 37 38 ans = -1; 39 40 memset(Q, 0, sizeof(Q)); 41 memset(v, 0, sizeof(v)); 42 memset(d, 0, sizeof(d)); 43 44 Q[1].x = sr, Q[1].y = sc; 45 v[sr][sc] = 1; 46 front = 1, rear = 2; 47 while (front < rear) 48 { 49 cur = Q[front++]; 50 if (cur.x == er && cur.y == ec) {ans = d[cur.x][cur.y]; break;} 51 for (i = 0; i < 4; ++i) 52 { 53 nst.x = cur.x + dir[i][0]; 54 nst.y = cur.y + dir[i][1]; 55 if (nst.x>=1 && nst.x<=r && nst.y>=1 && nst.y<=c) 56 { 57 if (m[nst.x][nst.y]=='0' && !v[nst.x][nst.y]) 58 { 59 Q[rear++] = nst; 60 v[nst.x][nst.y] = 1; 61 d[nst.x][nst.y] = d[cur.x][cur.y] + 1; 62 } 63 } 64 } 65 } 66 67 if (ans == -1) puts("No Path."); 68 else printf("%d\n", ans); 69 70 } 71 72 int main() 73 { 74 int T; 75 76 scanf("%d", &T); 77 while (T--) 78 { 79 read(); 80 solve(); 81 } 82 83 return 0; 84 }
//