您的位置:首页 > 产品设计 > UI/UE

杭电1242Rescue题(bfs+优先队列)

2013-06-23 11:05 302 查看

杭电1242Rescue题(bfs+优先队列)

题目链接~~>

这题是学习优先队列的第一题搞了好久才AC:


先介绍一下优先队列:

头文件:

#include<queue>
usingnamespacestd;

由大到小出队:

structzhang
{
intx,y;
friendbooloperator<(constzhang&a,constzhang&b)
{
returna.x<b.x;
}

};
priority_queue<zhang>q;
zhangcurrent;

由小到大出队:

           将上面的returna.x<b.x;中的"<"改为“>”;但传说中这种方法G++编译器编译不过;

(非本人)代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#defineN201
usingnamespacestd;

//优先队列解决,广度优先
structPersion
{
intx,y;
inttime;
friendbooloperator<(constPersion&a,constPersion&b)
{
returna.time>b.time;//">"返回队列中较小的元素;"<"则返回队列中较大的元素
}

};

intdir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
charmap

;
intvisited

;
intm,n;

intBFS(intx,inty)
{

priority_queue<Persion>q;
Persioncurrent,next;
memset(visited,0,sizeof(visited));

current.x=x;
current.y=y;
current.time=0;
visited[current.x][current.y]=1;
q.push(current);

while(!q.empty())
{

current=q.top();
q.pop();
for(inti=0;i<4;i++)
{
next.x=current.x+dir[i][0];
next.y=current.y+dir[i][1];

if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&map[next.x][next.y]!='#'&&!visited[next.x][next.y])
{

if(map[next.x][next.y]=='r')
returncurrent.time+1;

if(map[next.x][next.y]=='x')
next.time=current.time+2;
else
next.time=current.time+1;

visited[next.x][next.y]=1;
q.push(next);

}
}

}

return-1;
}

intmain()
{

inti,j;
Persionangle;

while(cin>>n>>m&&(m||n))
{

for(i=0;i<n;i++)
for(j=0;j<m;j++)
{

cin>>map[i][j];
if(map[i][j]=='a')
{
angle.x=i;
angle.y=j;
}
}

inttime=BFS(angle.x,angle.y);

if(time==-1)
cout<<"PoorANGELhastostayintheprisonallhislife."<<endl;
else
cout<<time<<endl;

}
return0;
}


 




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: