1 #include<stdio.h> 2 #include<string.h> 3 const int N = 30; 4 char map[N][N]; 5 struct node { 6 int dir, x, y, time, color; 7 }q[N * N * 5 * 4 * 10], cur, next, start, end; 8 int m, n; 9 bool judge(node cur) { 10 if(cur.x >=0 && cur. x < m && cur.y >=0 && cur.y < n) 11 return true; 12 else 13 return false; 14 } 15 bool v[N][N][5][4]; 16 int bfs(node start) { 17 memset(v, 0, sizeof(v)); 18 v[start.x][start.y][start.color][start.dir] = 1; 19 int rear = -1, front = 0; 20 q[++rear] = start; 21 while(front <= rear) { 22 cur = q[front++]; 23 //printf("x = %d y = %d color = %d dir = %d time = %d\n", cur.x, cur.y, cur.color, cur.dir, cur.time); 24 if(map[cur.x][cur.y] == 'T' && cur.color == 0) 25 return cur.time; 26 next = cur; next.time = cur.time + 1; 27 next.dir = (cur.dir + 1) % 4; 28 if(!v[next.x][next.y][next.color][next.dir]) { 29 v[next.x][next.y][next.color][next.dir] = 1; 30 q[++rear] = next; 31 } 32 next.dir = (cur.dir + 3) % 4; 33 if(!v[next.x][next.y][next.color][next.dir]) { 34 v[next.x][next.y][next.color][next.dir] = 1; 35 q[++rear] = next; 36 } 37 if(cur.dir == 0) { 38 next.x = cur.x - 1; 39 next.color = (cur.color + 1) % 5; 40 next.dir = cur.dir; 41 if(judge(next) && !v[next.x][next.y][next.color][next.dir] && map[next.x][next.y] != '#') { 42 v[next.x][next.y][next.color][next.dir] = 1; 43 q[++rear] = next; 44 } 45 } 46 else if(cur.dir == 1) { 47 next.y = cur.y + 1; 48 next.color = (cur.color + 1) % 5; 49 next.dir = cur.dir; 50 if(judge(next) && !v[next.x][next.y][next.color][next.dir] && map[next.x][next.y] != '#') { 51 v[next.x][next.y][next.color][next.dir] = 1; 52 q[++rear] = next; 53 } 54 } 55 else if(cur.dir == 2) { 56 next.x = cur.x + 1; 57 next.color = (cur.color + 1) % 5; 58 next.dir = cur.dir; 59 if(judge(next) && !v[next.x][next.y][next.color][next.dir] && map[next.x][next.y] != '#') { 60 v[next.x][next.y][next.color][next.dir] = 1; 61 q[++rear] = next; 62 } 63 } 64 else { 65 next.y = cur.y - 1; 66 next.color = (cur.color + 1) % 5; 67 next.dir = cur.dir; 68 if(judge(next) && !v[next.x][next.y][next.color][next.dir] && map[next.x][next.y] != '#') { 69 v[next.x][next.y][next.color][next.dir] = 1; 70 q[++rear] = next; 71 } 72 } 73 } 74 return -1; 75 } 76 int main() { 77 int ca = 1; 78 while(scanf("%d%d", &m, &n), m||n) { 79 for(int i = 0; i < m; ++i) { 80 scanf("%s", map[i]); 81 for(int j = 0; j < n; ++j) { 82 if(map[i][j] == 'S') { 83 start.x = i; 84 start.y = j; 85 start.dir = 0; 86 start.color = 0; 87 start.time = 0; 88 } 89 } 90 } 91 int ans = bfs(start); 92 if(ca != 1) printf("\n"); 93 printf("Case #%d\n", ca++); 94 if(ans == -1) 95 printf("destination not reachable\n"); 96 else 97 printf("minimum time = %d sec\n", ans); 98 } 99 return 0; 100 }
浙公网安备 33010602011771号