当前位置:编程学习 > C/C++ >>

hdu 2822 Dogs(优先队列)

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define N 1005
using namespace std;
char map[N][N];
int v[N][N],d[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
int begin_x,begin_y,end_x,end_y,n,m;
struct node
{
    int x,y,step;
    friend bool operator < (node a,node b)
    {
        return a.step > b.step;
    }
};
void bfs()
{
    memset(v,0,sizeof(v));
    priority_queue <node> q;
    node s,temp;
    s.x = begin_x;
    s.y = begin_y;
    s.step = 0;
    v[s.x][s.y] = 1;
    q.push(s);
    while(!q.empty())
    {
        temp = q.top();
        q.pop();
        if(s.x == end_x && s.y == end_y)
        {
            printf("%d\n",s.step);
            return ;
        }
        for(int i= 0 ; i < 4 ; i ++)
        {
            s = temp;
            s.x += d[i][0];
            s.y += d[i][1];
            if(s.x < 0 || s.x >= n || s.y < 0 || s.y >= m || v[s.x][s.y])
             continue;
            v[s.x][s.y] = 1;
            if(map[s.x][s.y] == '.') s.step ++;
            q.push(s);
        }
    }
}
int main()
{
    int i;
    while(scanf("%d%d",&n,&m) && (n + m))
    {
        for(i = 0 ; i < n ; i ++)
         scanf("%s",map[i]);
        scanf("%d%d%d%d",&begin_x,&begin_y,&end_x,&end_y);
        begin_x -- ; begin_y --; end_x -- ; end_y --;//题目给出的坐标都是从1开始计算的
        bfs();
    }
    return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,