题目链接 诡异的楼梯
5 5 **..T **.*. ..|.. .*.*. S....
如图所示的地图,|代表楼梯,每分钟移动一次方向,只能顺着楼梯的方向走,每次可以在 . 或S或T处停留,求从S到T的最小步数
没有什么难度,在楼梯的地方模拟清楚就行,把方向的各个情况弄清楚
记录时间差,判断到达楼梯时的方向,
当是|的时候,只能沿着上下方向走,
当是—时只能沿着左右走,
!要注意的是 可以在当前点等待,此时步数+1,退回到之前的点等待一分钟,就可以上楼梯的了
#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <queue>
using namespace std;
const int maxn=25;
char g[maxn][maxn];
bool vis[maxn][maxn];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
int m,n,sx,sy,ex,ey,dir;
struct node
{
int x,y,step;
};
bool check(int x,int y)
{
if(x<0||y<0||x>m-1||y>n-1)return false;
if(vis[x][y])return false;
if(g[x][y]=='*')return false;
return true;
}
int bfs()
{
queue<node>q;
memset(vis,0,sizeof(vis));
node cur,next;
cur.x=sx;cur.y=sy;cur.step=0;
q.push(cur);
vis[sx][sy]=true;
while(!q.empty()){
cur=q.front();
q.pop();
int s=cur.step%2;
if(g[cur.x][cur.y]=='T')return cur.step;
for(int i=0;i<4;i++){
int nx=cur.x+dx[i];
int ny=cur.y+dy[i];
if(check(nx,ny)){
if(g[nx][ny]=='|'){
if(s){
if(i==0||i==1){
nx=nx-dx[i];//不能上楼梯,退回等待
ny=ny-dy[i];
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
else{
nx=nx+dx[i];
ny=ny+dy[i];
if(check(nx,ny)){
vis[nx][ny]=true;
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
}
}
else{
if(i==2||i==3){
nx=nx-dx[i];//不能上楼梯,退回等待
ny=ny-dy[i];
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
else{
nx=nx+dx[i];
ny=ny+dy[i];
if(check(nx,ny)){
vis[nx][ny]=true;
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
}
}
}
else if(g[nx][ny]=='-'){
if(s){
if(i==2||i==3){
nx=nx-dx[i];
ny=ny-dy[i];
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
else{
nx=nx+dx[i];
ny=ny+dy[i];
if(check(nx,ny)){
vis[nx][ny]=true;
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
}
}
else{
if(i==0||i==1){
nx=nx-dx[i];
ny=ny-dy[i];
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
else{
nx=nx+dx[i];
ny=ny+dy[i];
if(check(nx,ny)){
vis[nx][ny]=true;
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
}
}
}
else{
vis[nx][ny]=true;
next.x=nx;
next.y=ny;
next.step=cur.step+1;
q.push(next);
}
}
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d%d",&m,&n)!=EOF){
for(int i=0;i<m;i++){
scanf("%s",g[i]);
for(int j=0;j<n;j++){
if(g[i][j]=='S'){
sx=i;sy=j;
}
}
}
printf("%d\n",bfs());
}
return 0;
}