您的位置:首页 > 其它

hdu 1180 诡异的楼梯(bfs+优先队列)

2013-08-16 10:47 447 查看
诡异的电梯,实在诡异!!!

分析到诡异的地方时,把我都搞迷了!

看你别人的代码!才知道这样分析!!!

这题关键判断电梯的方向!!!人可以为了减少时间停在原地不动等电梯改变方向!!!

#include<stdio.h>

#include<string.h>

#include<queue>

using namespace std;

struct node

{

int x,y,step;

friend bool operator<(node a,node b)

{

return a.step>b.step;

}

};

char map[1010][1010];

int mark[1010][1010];

int dir[4][2]={1,0,-1,0,0,-1,0,1};

int n,m;

int judge(int x,int y)

{

if(x>=0&&x<n&&y>=0&&y<m)

return 1;

return 0;

}

int bfs(int sx,int sy)

{

int i;

int x,y;

priority_queue<node>Q;

node cur,next;

cur.x=sx;cur.y=sy;cur.step=0;

Q.push(cur);

while(!Q.empty())

{

cur=Q.top();

Q.pop();

for(i=0;i<4;i++)

{

x=cur.x+dir[i][0];

y=cur.y+dir[i][1];

next.step=cur.step+1;

if(judge(x,y))

{

if(map[x][y]=='-'||map[x][y]=='|')

{

if(cur.step%2==0)

{

if((map[x][y]=='-'&&i>1)||(map[x][y]=='|'&&i<2))

{

x+=dir[i][0];

y+=dir[i][1];

}

else

{

next=cur;

next.step++;

Q.push(next);

continue;

}

}

else

{

if((map[x][y]=='|'&&i>1)||(map[x][y]=='-'&&i<2))

{

x+=dir[i][0];

y+=dir[i][1];

}

else

{

next=cur;

next.step++;

Q.push(next);

continue;

}

}

}

if(mark[x][y]==0&&judge(x,y))

{

if(map[x][y]=='T')

return cur.step+1;

else if(map[x][y]=='.')

{

mark[x][y]=1;

next.x=x;next.y=y;next.step=cur.step+1;

Q.push(next);

}

}

}

}

}

return -1;

}

int main()

{

int ans;

while(scanf("%d %d",&n,&m)!=EOF)

{

int sx,sy,i,j;

memset(mark,0,sizeof(mark));

for(i=0;i<n;i++)

scanf("%s",map[i]);

for(i=0;i<n;i++)

for(j=0;j<m;j++)

if(map[i][j]=='S')

sx=i,sy=j;

ans=bfs(sx,sy);

printf("%d\n",ans);

}

return 0;

}

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1180
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: