您的位置:首页 > 其它

HDU 1180 诡异的楼梯(BFS,用优先队列过)

2015-09-25 16:56 399 查看
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
char map[25][25];
int PRE[25][25];
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int m,n;
int sx,sy,ex,ey;
struct node
{
int x;
int y;
int step;
bool operator<(const node &s)const
{
return step>s.step;
}
};
int bfs()
{
struct node now,pre;
priority_queue<node>Q;
pre.x=sx;
pre.y=sy;
pre.step=0;
Q.push(pre);
while(!Q.empty())
{
pre=Q.top();
Q.pop();
if(pre.x==ex&&pre.y==ey&&map[pre.x][pre.y]=='T')
{
return pre.step;
}
for(int i=0; i<4; i++)
{
now.x=pre.x+dir[i][0];
now.y=pre.y+dir[i][1];
now.step=pre.step+1;
if(map[now.x][now.y]=='|')//当前走到的地理位置
{
if(now.x==pre.x&&((pre.step)&1==0))//左右走的时候
{
now.step+=1;//停留一下,等它回复的时候,就可以走了
}
if(now.y==pre.y&&((pre.step)&1==1))//上下走的时候
{
now.step+=1;//停留一下,等它回复的时候,就可以走了
}
now.x=now.x+dir[i][0];
now.y=now.y+dir[i][1];
}
if(map[now.x][now.y]=='-')
{
if(now.x==pre.x&&((pre.step)&1==1))//左右走的时候
{
now.step+=1;
}
if(now.y==pre.y&&((pre.step)&1==0))//上下走的时候
{
now.step+=1;
}
now.x=now.x+dir[i][0];
now.y=now.y+dir[i][1];
}
if(now.x>=0&&now.x<m&&now.y>=0&&now.y<n&&PRE[now.x][now.y]<now.step&&(map[now.x][now.y]=='.'||map[now.x][now.y]=='S'||map[now.x][now.y]=='T'))//判断路径是否合法
{
PRE[now.x][now.y]=now.step;//记录上一步的步数,来给下一步都的时候判断用,当前一步小于后一步,可以走,否则不可以走
Q.push(now);
}
else
{
continue;
}

}
}
return -1;
}
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
memset(PRE,0,sizeof(PRE));
int i,j;
for(i=0; i<m; i++)
{
scanf("%s",map[i]);
for(j=0; j<n; j++)
{
if(map[i][j]=='S')
{
sx=i;
sy=j;
}
if(map[i][j]=='T')
{
ex=i;
ey=j;
}
}
}
int t=bfs();
printf("%d\n",t);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: