Hdu2822Dogs bfs+优先队列

来源:互联网 发布:windows phone 官网 编辑:程序博客网 时间:2024/04/29 00:04

代码:

#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;

}

 

0 0
原创粉丝点击