zoj 1649 BFS

来源:互联网 发布:淘宝网狗狗宠物店 编辑:程序博客网 时间:2024/06/05 17:03

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=649

我觉得这题写的很好

以下为我的代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;


const int INF=55555555;
const int sizen=500;
struct ele
{
    int x;
    int y;
}t,s;
char Map[sizen][sizen];
int mapp[sizen][sizen];
int d[4][2]={1,0,-1,0,0,1,0,-1};


void bfs(int x,int y,int n,int m)
{
    int i;
    queue<ele>p;
    t.x=x;
    t.y=y;
    p.push(t);
    while(p.size())
    {
        t=p.front();
        p.pop();
        for(i=0;i<4;i++)
        {
            x=t.x+d[i][0];
            y=t.y+d[i][1];
            if(x>=0&&x<n&&y>=0&&y<m&&Map[x][y]!='#')
            {
                if(Map[x][y]=='.'||Map[x][y]=='a')
                if(mapp[x][y]>mapp[t.x][t.y]+1)
                {
                    //printf("%d %d\n",x,y);
                    mapp[x][y]=mapp[t.x][t.y]+1;
                    s.x=x;
                    s.y=y;
                    p.push(s);
                }
                if(Map[x][y]=='x')
                if(mapp[x][y]>mapp[t.x][t.y]+2)
                {
                    mapp[x][y]=mapp[t.x][t.y]+2;
                    s.x=x;
                    s.y=y;
                    p.push(s);
                }
            }
        }
    }
}


int main()
{
    int sx,sy;
    int ex,ey;
    int n,m;
    int i,j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i=0;i<n;i++)
            scanf("%s",Map[i]);
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
            {
                if(Map[i][j]=='r')
                    sx=i,sy=j;
                mapp[i][j]=INF;
                if(Map[i][j]=='a')
                    ex=i,ey=j;
            }
        mapp[sx][sy]=0;
        bfs(sx,sy,n,m);
        if(mapp[ex][ey]!=INF)
            printf("%d\n",mapp[ex][ey]);
        else
            printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
    return 0;
}

0 0
原创粉丝点击