Uva--10047 (BFS,附加条件)
2014-07-08 00:56:49
题意&思路:题意概述:给出图(起点,终点,障碍),让你从起点开始走到终点,每走一步或者每转90度的弯时间数加一,且要求总步数是5的倍数。问最小的时间?
思路:用BFS,加上vis[row][col][dir][s](s表示步数%5)这个标记数组,就可以做了。。。。一开始没有考虑到转弯也要记录状态到vis,怒无限WA。
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <queue> 5 #include <cmath> 6 using namespace std; 7 const int maxn = 1000000000; 8 9 int row,col,sr,sc,er,ec,tmin,vis[30][30][4][5]; 10 int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};//上,右,下,左 11 char g[30][30]; 12 struct node{ 13 int r,c,d,t,s; 14 }; 15 bool Bfs(){ 16 node a,b; 17 queue<node> q; 18 a.r = sr; 19 a.c = sc; 20 a.d = a.t = a.s = 0; 21 vis[a.r][a.c][a.d][a.s] = 1; 22 q.push(a); 23 while(!q.empty()){ 24 a = q.front(); 25 q.pop(); 26 if(a.r == er && a.c == ec && a.s == 0){ 27 tmin = a.t; 28 return true; 29 } 30 //左转 31 b.r = a.r,b.c = a.c,b.s = a.s; 32 b.d = (a.d + 3) % 4; 33 b.t = a.t +1; 34 if(!vis[b.r][b.c][b.d][b.s]){ 35 q.push(b); 36 vis[b.r][b.c][b.d][b.s] = 1; 37 } 38 //右转 39 b.r = a.r,b.c = a.c,b.s = a.s; 40 b.d = (a.d + 1) % 4; 41 b.t = a.t + 1; 42 if(!vis[b.r][b.c][b.d][b.s]){ 43 q.push(b); 44 vis[b.r][b.c][b.d][b.s] = 1; 45 } 46 //前进 47 b.r = a.r + dir[a.d][0]; 48 b.c = a.c + dir[a.d][1]; 49 b.d = a.d; 50 b.t = a.t + 1; 51 b.s = (a.s + 1) % 5; 52 if(b.r >= 0 && b.r < row && b.c >= 0 && b.c < col && 53 g[b.r][b.c] != '#' && !vis[b.r][b.c][b.d][b.s]){ 54 q.push(b); 55 vis[b.r][b.c][b.d][b.s] = 1; 56 } 57 } 58 return false; 59 } 60 int main(){ 61 int Case = 0; 62 while(scanf("%d %d",&row,&col) == 2){ 63 getchar(); 64 if(!row && !col) break; 65 memset(g,0,sizeof(g)); 66 for(int i = 0; i < row; ++i){ 67 fgets(g[i],30,stdin); 68 for(int j = 0; j < col; ++j){ 69 if(g[i][j] == 'S') 70 sr = i,sc = j; 71 else if(g[i][j] == 'T') 72 er = i,ec = j; 73 } 74 } 75 if(Case) puts(""); 76 printf("Case #%d\n",++Case); 77 memset(vis,0,sizeof(vis)); 78 if(Bfs()) 79 printf("minimum time = %d sec\n",tmin); 80 else 81 printf("destination not reachable\n"); 82 } 83 return 0; 84 }