HDU 1026 Ignatius and the Princess I(BFS)
复杂啊,这到底是模拟题还是BFS啊。。。。数组开小RE一次,2Y。。。调试了好久啊。
1 #include <stdio.h> 2 #include <string.h> 3 #define N 1000001 4 char p[101][101]; 5 int o[101][101],key[101][101];// key标记,o标记 6 int r[100001],c[100001],ti[100001];//ti记录时间 7 int past[100001],load[100001];//记录路径 8 int main() 9 { 10 int n,m,i,j,k,start,end,num,z; 11 int a[4] = {0,0,1,-1}; 12 int b[4] = {1,-1,0,0}; 13 while(scanf("%d%d%*c",&n,&m)!=EOF) 14 { 15 memset(o,0,sizeof(o)); 16 memset(key,0,sizeof(key)); 17 for(i = 0; i <= n-1; i ++) 18 gets(p[i]); 19 if(p[n-1][m-2] == 'X'&&p[n-2][m-1] == 'X')//小剪枝 20 { 21 printf("God please help our poor hero.\n"); 22 printf("FINISH\n"); 23 continue; 24 } 25 for(i = 0; i <= n-1; i ++) 26 for(j = 0; j <= m-1; j ++) 27 { 28 if(p[i][j] == 'X') 29 { 30 o[i][j] = N; 31 key[i][j] = 1; 32 } 33 else if(p[i][j] == '.') 34 o[i][j] = 0; 35 else if(p[i][j] >= '0'&&p[i][j] <= '9') 36 o[i][j] = p[i][j] - '0'; 37 } 38 start = end = 1; 39 r[1] = c[1] = 0; 40 ti[1] = o[0][0]; 41 num = 0; 42 z = 0; 43 key[0][0] = 1; 44 while(start <= end)//BFS 45 { 46 j = 1; 47 if(z) break; 48 for(i = start; i <= end&&!z; i ++) 49 { 50 if(ti[i] == 0) 51 { 52 for(k = 0; k <= 3&&!z; k ++) 53 { 54 if(r[i]+a[k]>=0&&c[i]+b[k]>=0&&r[i]+a[k]<=n-1&&c[i]+b[k]<=m-1) 55 { 56 if(key[r[i]+a[k]][c[i]+b[k]] == 0) 57 { 58 r[j + end] = r[i]+a[k]; 59 c[j + end] = c[i]+b[k]; 60 ti[j + end] = o[r[i]+a[k]][c[i]+b[k]]; 61 key[r[i]+a[k]][c[i]+b[k]] = 1; 62 past[j+end] = i; 63 if(r[j + end] == n-1&&c[end + j] == m-1&&ti[j+end] == 0) 64 { 65 z = 1; 66 } 67 j ++; 68 } 69 } 70 } 71 } 72 else 73 { 74 r[j + end] = r[i]; 75 c[j + end] = c[i]; 76 ti[j + end] = ti[i] - 1; 77 past[j+end] = i; 78 if(r[j + end] == n-1&&c[end + j] == m-1&&ti[j+end] == 0) 79 { 80 z = 1; 81 } 82 j ++; 83 } 84 } 85 start = end + 1; 86 end = end + j - 1; 87 num ++; 88 } 89 if(z) 90 { 91 printf("It takes %d seconds to reach the target position, let me show you the way.\n",num); 92 load[0] = end;//找路径 93 for(i = 1;;i ++) 94 { 95 if(past[load[i-1]] == 1) 96 { 97 load[i] = 1; 98 break; 99 } 100 else 101 load[i] = past[load[i-1]]; 102 } 103 for(j = i;j >= 1;j --) 104 { 105 printf("%ds:",i-j+1); 106 if(r[load[j]] == r[load[j-1]]&&c[load[j]] == c[load[j-1]]) 107 printf("FIGHT AT (%d,%d)\n",r[load[j]],c[load[j]]); 108 else 109 printf("(%d,%d)->(%d,%d)\n",r[load[j]],c[load[j]],r[load[j-1]],c[load[j-1]]); 110 } 111 printf("FINISH\n"); 112 } 113 else 114 printf("God please help our poor hero.\nFINISH\n"); 115 } 116 return 0; 117 }