UVA10047 【The Monocycle】
阿新 • • 發佈:2018-11-08
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 char a[30][30]; 7 int vis[30][30][4][5]; 8 int n,m; 9 int dx[4]={-1,0,1,0}; 10 int dy[4]={0,1,0,-1}; 11 struct node{ 12 int x,y,di,co,t; 13 node(int xx,int yy,int d,intc,int st) 14 { 15 x=xx;y=yy;di=d;co=c;t=st; 16 } 17 }; 18 queue<node> q; 19 void bfs() 20 { 21 while(!q.empty()) 22 { 23 node u=q.front(); 24 q.pop(); 25 if(a[u.x][u.y]=='T'&&u.co==0) 26 { 27 printf("minimum time = %d sec\n",u.t); 28 return; 29 } 30 int x=u.x,y=u.y,co=u.co; 31 int di=(u.di+1)%4;//向右轉 32 if(!vis[x][y][di][co]) 33 { 34 vis[x][y][di][co]=1; 35 q.push(node(x,y,di,co,u.t+1)); 36 } 37 di=(u.di+3)%4;//向左轉 38 if(!vis[x][y][di][co])39 { 40 vis[x][y][di][co]=1; 41 q.push(node(x,y,di,co,u.t+1)); 42 } 43 di=u.di;//前進 44 x+=dx[di];y+=dy[di]; 45 co=(co+1)%5;//下一種顏色 46 if(x<n&&x>=0&&y<m&&y>=0&&a[x][y]!='#'&&!vis[x][y][di][co]) 47 { 48 q.push(node(x,y,di,co,u.t+1)); 49 vis[x][y][di][co]=1; 50 } 51 } 52 printf("destination not reachable\n"); 53 } 54 int main() 55 { 56 int ss=1; 57 while(scanf("%d%d",&n,&m)&&n&&m) 58 { 59 if(ss>1) printf("\n"); 60 memset(vis,0,sizeof(vis)); 61 while(!q.empty()) q.pop(); 62 for(int i=0;i<n;i++) 63 for(int j=0;j<m;j++) 64 { 65 cin>>a[i][j]; 66 if(a[i][j]=='S') 67 { 68 q.push(node(i,j,0,0,0)); 69 vis[i][j][0][0]=1; 70 } 71 } 72 printf("Case #%d\n",ss++); 73 bfs(); 74 } 75 return 0; 76 }