标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 12487 Accepted Submission(s): 3120
#include<cstdio> #include<cstring> #include<algorithm> #include<math.h> #include<queue> using namespace std; typedef long long LL; char graph[25][25]; bool vis[25][25]; struct Node { int x,y,step; }; Node s,t; int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}}; int n,m; bool check(int x,int y) { if(x<0||x>=n||y<0||y>=m||vis[x][y]||graph[x][y]==‘*‘) return false; return true; } int bfs() { memset(vis,false,sizeof(vis)); queue<Node> q; vis[s.x][s.y]=true; q.push(s); while(!q.empty()) { Node node = q.front(); q.pop(); if(node.x==t.x&&node.y==t.y) { return node.step; } Node next; for(int i=0; i<4; i++) { next.x = node.x+dir[i][0]; next.y = node.y+dir[i][1]; next.step=node.step+1; if(!check(next.x,next.y)) continue; if(graph[next.x][next.y]==‘.‘) { vis[next.x][next.y]=true; q.push(next); } if(graph[next.x][next.y]==‘|‘) { if((next.step%2==1)&&(i==0||i==1)) ///now this place change to ‘-‘ { next.x+=dir[i][0]; next.y+=dir[i][1]; if(check(next.x,next.y)){ vis[next.x][next.y]=true; q.push(next); } } else if((next.step%2==0)&&(i==2||i==3)) ///stay ‘|‘ { next.x+=dir[i][0]; next.y+=dir[i][1]; if(check(next.x,next.y)){ vis[next.x][next.y]=true; q.push(next); } }else{ ///隐含条件,等下一分钟 next.x= node.x; next.y = node.y; q.push(next); } } if(graph[next.x][next.y]==‘-‘) { if((next.step%2==1)&&(i==2||i==3)) ///now this place change to ‘|‘ { next.x+=dir[i][0]; next.y+=dir[i][1]; if(check(next.x,next.y)){ vis[next.x][next.y]=true; q.push(next); } } else if((next.step%2==0)&&(i==0||i==1)) ///stay ‘-‘ { next.x+=dir[i][0]; next.y+=dir[i][1]; if(check(next.x,next.y)){ vis[next.x][next.y]=true; q.push(next); } }else{ ///等下一分钟 next.x= node.x; next.y = node.y; q.push(next); } } } } return -1; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0; i<n; i++) { scanf("%s",graph[i]); for(int j=0; j<m; j++) { if(graph[i][j]==‘S‘) { s.x = i,s.y = j,s.step=0; graph[i][j]=‘.‘; } else if(graph[i][j]==‘T‘) { t.x = i,t.y = j; graph[i][j]=‘.‘; } } } int res = bfs(); printf("%d\n",res); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5572059.html