hdu 2822 Dogs(优先队列)

题目链接:hdu2822

会优先队列话这题很容易AC。。。。

#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
",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;
}


原文地址:https://www.cnblogs.com/dyllove98/p/3220133.html