传送门:
http://acm.hdu.edu.cn/showproblem.php?pid=1180
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 18382 Accepted Submission(s): 4864
#include<bits/stdc++.h> using namespace std; #define max_v 25 struct node { int x,y,t; }; char G[max_v][max_v]; int vis[max_v][max_v]; int dir[4][2]= {{0,1},{1,0},{0,-1},{-1,0}}; int n,m,sx,sy,fx,fy,tme; bool isout(int x,int y)//判断能否继续搜 { if(x<0||x>=n||y<0||y>=m)//越界 return 1; if(vis[x][y]==1)//搜过 return 1; if(G[x][y]==‘*‘)//障碍物 return 1; return 0; } bool isgo(node t,char x,int d)//判断是不是需要等待楼梯转动 { t.t+=1; if(x==‘|‘) { if(d%2==0&&t.t%2==0) return 1; if(d%2==1&&t.t%2==1) return 1; return 0; } else if(x==‘-‘) { if(d%2==1&&t.t%2==0) return 1; if(d%2==0&&t.t%2==1) return 1; return 0; } } void bfs() { memset(vis,0,sizeof(vis));//是否走过标记位重置 queue<node> q; node p,next; p.x=sx;//起点初始化 p.y=sy; p.t=0; vis[p.x][p.y]=1; q.push(p);//队列初始化 while(!q.empty()) { p=q.front(); q.pop(); if(p.x==fx&&p.y==fy)//判断是否到达终点 { tme=p.t; return ; } //四个方向搜 for(int i=0; i<4; i++) { next.x=p.x+dir[i][0]; next.y=p.y+dir[i][1]; //判断越界 if(isout(next.x,next.y)) continue; if(G[next.x][next.y]==‘.‘)//可行点之一 . { next.t=p.t+1; vis[next.x][next.y]=1; q.push(next); } else //如果是楼梯 { if(isout(next.x+dir[i][0],next.y+dir[i][1]))//判断楼梯对面点能不能走 continue; if(isgo(p,G[next.x][next.y],i))//楼梯不需要等,直接走 { next.x+=dir[i][0]; next.y+=dir[i][1]; next.t=p.t+1; vis[next.x][next.y]=1; q.push(next); } else //需要等楼梯翻转过来才能走 { next.x=p.x; next.y=p.y; next.t=p.t+1; q.push(next); } } } } } int main() { while(cin>>n>>m) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin>>G[i][j]; if(G[i][j]==‘S‘)//找起点 { G[i][j]=‘.‘; sx=i; sy=j; } if(G[i][j]==‘T‘)//找终点 { G[i][j]=‘.‘; fx=i; fy=j; } } } bfs(); cout<<tme<<endl; } return 0; }
HDU 1180 诡异的楼梯(超级经典的bfs之一,需多回顾)
原文:https://www.cnblogs.com/yinbiao/p/9349599.html