Question Link: Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1180
Theme: There are a bunch of stairs in the maze, and the stairs change horizontally and vertically. These stairs change to the opposite state at an odd number of times, and the next point in the forward direction will be reached by the way through the stairs (skip the stairs ).
At the same time, you can wait in the same place and ask the minimum time to reach the destination.
Solutions:
An interesting question.
Or BFS first. For a stair, the change function is responsible for calculating the new x and y that can be reached when the stair is exited, and then determining whether the flight is out of the border or not.
Note that in '. 'points can be waited in the same place, and additional push is required. This is also the reason why the data cannot go out of the maze. Otherwise, the data cannot go out of the maze, BFS will not stop at one point.
Then, the program burst.
#include "cstdio"#include "string"#include "cstring"#include "iostream"#include "queue"using namespace std;char map[25][25];int n,m,sx,sy,ex,ey,dir[4][2]={-1,0,1,0,0,-1,0,1},vis[25][25];struct status{ int x,y,dep; status(int x,int y,int dep):x(x),y(y),dep(dep) {}};status change(status s,int dir,char c,int dep){ if(dep%2) c=(c==‘|‘?‘-‘:‘|‘); if(c==‘|‘) { if(dir==0) return status(s.x-1,s.y,0); if(dir==1) return status(s.x+1,s.y,0); if(dir==2||dir==3) return status(-1,-1,0); } if(c==‘-‘) { if(dir==0||dir==1) return status(-1,-1,0); if(dir==2) return status(s.x,s.y-1,0); if(dir==3) return status(s.x,s.y+1,0); }}int bfs(int x,int y){ queue<status> Q; Q.push(status(x,y,0)); vis[x][y]=true; while(!Q.empty()) { status t=Q.front();Q.pop(); for(int s=0;s<4;s++) { int X=t.x+dir[s][0],Y=t.y+dir[s][1]; if(X<1||X>n||Y<1||Y>m||vis[X][Y]||map[X][Y]==‘*‘) continue; if(map[X][Y]==‘|‘||map[X][Y]==‘-‘) { status nw=change(status(X,Y,0),s,map[X][Y],t.dep); X=nw.x;Y=nw.y; } if(X<1||X>n||Y<1||Y>m||vis[X][Y]||map[X][Y]==‘*‘) continue; vis[X][Y]=true; if(X==ex&&Y==ey) return t.dep+1; Q.push(status(X,Y,t.dep+1)); } if(map[t.x][t.y]!=‘|‘||map[t.x][t.y]!=‘-‘) Q.push(status(t.x,t.y,t.dep+1)); } return -1;}int main(){ //freopen("in.txt","r",stdin); ios::sync_with_stdio(false); string tt; while(cin>>n>>m) { memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) { cin>>tt; for(int j=0;j<tt.size();j++) { map[i][j+1]=tt[j]; if(tt[j]==‘S‘) {sx=i;sy=j+1;} if(tt[j]==‘T‘) {ex=i;ey=j+1;} } } int ans=bfs(sx,sy); cout<<ans<<endl; }}
11891440 |
01:13:57 |
Accepted |
1180 |
15 ms |
308 K |
2067 B |
C ++ |
Physcal |
HDU 1180 (BFS search)