Problem A: The Monocycle
A monocycle is a cycle that runs on one wheel and the one we will be considering is a bit more special. It has a solid wheel colored with five different colors as shown in the figure:Problem A: The Monocycle |



Before he starts his ride, please help him find out whether the destination is reachable and if so the minimum amount of time he will require to reach it.
Input
The input may contain multiple test cases.The first line of each test case contains two integers M and N (


Output
For each test case in the input first print the test case number on a separate line as shown in the sample output. If the target location can be reached by the cyclist print the minimum amount of time (in seconds) required to reach it exactly in the format shown in the sample output, otherwise, print ``destination not reachable".Print a blank line between two successive test cases.
Sample Input
1 3 S#T 10 10 #S.......# #..#.##.## #.##.##.## .#....##.# ##.##..#.# #..#.##... #......##. ..##.##... #.###...#. #.....###T 0 0
Sample Output
Case #1 destination not reachable Case #2 minimum time = 49 sec
Miguel Revilla
2000-12-26
shortest path, BFS
#include<stdio.h>
#include<cstring>
#include<queue>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define MAXN 25
#define DBG 0
using namespace std;
int N,M,cases=1,dir[4][2];
char maz[MAXN][MAXN+1];
bool dps[MAXN][MAXN][4][5];
struct Node{
Node(int a,int b,int c,int d,int e):x(a),y(b),face(c),wheel(d),dis(e){}
int face,x,y,dis,wheel;
};
void init(){
dir[0][0]=-1,dir[1][1]=-1,dir[2][0]=1,dir[3][1]=1;
}
bool valid(int a,int b){return a>=0&&a<N&&b>=0&&b<M;}
void ans(){
int a,b,c,d,x,y,e,w,si,sj,ei,ej,nw,nd[2];
bool ok=0;
memset(dps,0,sizeof(dps));
rep(i,N)rep(j,M){
if(maz[i][j]=='S')si=i,sj=j;
if(maz[i][j]=='T')ei=i,ej=j;}
queue<Node>q;
q.push(Node(si,sj,0,0,0)); //face north, wheel zero
while(q.size()){
a=q.front().x,b=q.front().y,c=q.front().face,w=q.front().wheel,
d=q.front().dis,q.pop();
if(DBG)printf("bfs a b face wheel dis %d %d %d %d %d\n",a,b,c,w,d);
dps[a][b][c][w]=1;
if(a==ei&&b==ej&&w==0){ok=1;break;}
nd[0]=(c+1)%4,nd[1]=(c-1)<0?3:c-1;
rep(i,2) //direction
if(!dps[a][b][nd[i]][w]){
dps[a][b][nd[i]][w]=1;
q.push(Node(a,b,nd[i],w,d+1));}
x=a+dir[c][0],y=b+dir[c][1],nw=(w+1)%5; //walk
if(valid(x,y)&&maz[x][y]!='#'&&!dps[x][y][c][nw]){
dps[x][y][c][nw]=1;
q.push(Node(x,y,c,nw,d+1));}
}
printf("Case #%d\n",cases++);
if(ok)printf("minimum time = %d sec\n",d);
else printf("destination not reachable\n");
}
int main(){
int a,b,c;
bool ll=0;
init();
while(scanf("%d%d",&N,&M)==2){
if(DBG)printf("N M %d %d\n",N,M);
if(N+M==0)break;
rep(i,N)scanf("%s",maz[i]);
if(ll)printf("\n");ll=1;ans();
}
return 0;
}
沒有留言:
張貼留言