1. 程式人生 > >hdu 1180 詭異的樓梯(bfs+優先佇列)

hdu 1180 詭異的樓梯(bfs+優先佇列)

詭異的電梯,實在詭異!!!

分析到詭異的地方時,把我都搞迷了!

看你別人的程式碼!才知道這樣分析!!!

這題關鍵判斷電梯的方向!!!人可以為了減少時間停在原地不動等電梯改變方向!!!

#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