您的位置:首页 > 其它

hdu - 2822 Dogs (优先队列+bfs)

2015-06-02 21:13 561 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2822

给定起点和终点,问从起点到终点需要挖几次只有从# 到 .或者从. 到 . 才需要挖一次。

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 1001;
int n,m;
int sx,sy,ex,ey;
char maze[maxn][maxn];
int vis[maxn][maxn];
int dir[4][2]={-1,0,1,0,0,1,0,-1};
struct point
{
int x,y,step;
char z;
bool operator < (const point a) const
{
return step>a.step;
}
};

int bfs()
{
// printf("%d %d\n",a,b);
for(int i=0;i<=n;i++)
for(int j=0;j<=m;j++)
vis[i][j]=1<<29;
priority_queue<point>que;
point s;
s.x=sx;s.y=sy;s.step=0;s.z='X';
que.push(s);
vis[s.x][s.y]=0;
while(!que.empty())
{
point e=que.top();que.pop();
//printf("%d %d %d\n",e.x,e.y,e.step);
if(e.x==ex&&e.y==ey) return e.step;
for(int i=0;i<4;i++)
{
s=e;
s.x=e.x+dir[i][0];
s.y=e.y+dir[i][1];
if(s.x>=0&&s.x<n&&s.y>=0&&s.y<m)
{
if(maze[s.x][s.y]=='X') s.step=e.step;
else if(maze[s.x][s.y]=='.') s.step=e.step+1;
if(s.step<vis[s.x][s.y])
{
vis[s.x][s.y]=s.step;
que.push(s);
}
}
}
}
}

int main()
{
//freopen("a.txt","r",stdin);
while(~scanf("%d%d",&n,&m))
{
if(n==0&&m==0) break;
for(int i=0;i<n;i++)
{
scanf("%s",maze[i]);
// printf("%s\n",maze[i]);
}
scanf("%d %d",&sx,&sy);
scanf("%d %d",&ex,&ey);
//printf("%d%d%d%d\n",sx,sy,ex,ey);
sx--,sy--,ex--,ey--;
printf("%d\n",bfs());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: