Hdu2822Dogs bfs+优先队列


代码:

#include<iostream>

#include<cstdio>

#include<cstring>

#include<queue>

using namespace std;

#define maxn 1010

char str[maxn][maxn];

struct node

{

    friend bool operator < (node a,node b)

    {

        return a.num>b.num;

    }

    int x,y;

    int num;

};

priority_queue<struct node> que;

int vis[maxn][maxn];

int sx,sy,tx,ty;

int dx[4]={-1,0,1,0};

int dy[4]={0,1,0,-1};

int row,cow;

int bfs()

{

    int i;

    while(que.size())

    que.pop();

    memset(vis,0,sizeof(vis));

    struct node first={sx,sy,0};

    que.push(first);

    vis[sx][sy]=1;

    while(que.size())

    {

        struct node now=que.top();

        que.pop();

        if(now.x==tx&&now.y==ty)

        {

            printf("%d\n",now.num);

            return 1;

        }

        int nx,ny;

        for(i=0;i<4;i++)

        {

            nx=now.x+dx[i];

            ny=now.y+dy[i];

            if(nx<=row&&nx>0&&ny>0&&ny<=cow&&!vis[nx][ny])

            {

                if(str[nx][ny]=='.')

                {

                    struct node next={nx,ny,now.num+1};

                    que.push(next);

                    vis[nx][ny]=1;

                }

                else if(str[nx][ny]=='X')

                {

                    struct node next={nx,ny,now.num};

                    que.push(next);

                    vis[nx][ny]=1;

                }

            }

        }

    }

    return 0;

}

 

int main()

{

    while(scanf("%d%d",&row,&cow)!=EOF)

    {

        if(!row&&!cow)

        break;

        int i;

        for(i=1;i<=row;i++)

          scanf("%s",&str[i][1]);

        scanf("%d%d%d%d",&sx,&sy,&tx,&ty);

        bfs();

    }

    return 0;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值