簡單BFS ZOJ 1649 Rescue

題意:r->a用時最少,經過'x'需2s,經過'.'1s.

思路:用BFS,但是,顯然,走的步數少並不代表用的時間少。因此,標記走到每個點用的最少時間,若下次要走到該點,必須比該點用時更少(同時更新該點)。

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <string.h>
#include <map>
#include <set>
using namespace std;
#define maxn 100005
#define inff  1000000000
char mat[205][205];
int n,m,stx,sty,enx,eny,mins;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct node {
 int x,y,step;
}tx,ty;
int v[205][205];
void bfs()
{
    queue<node>q;
    tx.x=stx;
    tx.y=sty;
    tx.step=0;
    q.push(tx);
    while(!q.empty())
    {
        tx=q.front();
        q.pop();
        if(tx.x==enx&&tx.y==eny)
        {
            mins=min(tx.step,mins);
            continue;
        }
        for(int i=0;i<4;i++)
        {
            ty.x=tx.x+dir[i][0];
            ty.y=tx.y+dir[i][1];
            if(ty.x>=0&&ty.x<n&&ty.y>=0&&ty.y<m&&mat[ty.x][ty.y]!='#')
            {

                if(mat[ty.x][ty.y]=='x')
                {

                    ty.step=tx.step+2;
                    if(ty.step<v[ty.x][ty.y])
                    {
                        v[ty.x][ty.y]=ty.step;
                        q.push(ty);
                    }
                }
                else if(mat[ty.x][ty.y]=='.'||mat[ty.x][ty.y]=='a')
                {
                    ty.step=tx.step+1;
                    if(ty.step<v[ty.x][ty.y])
                    {
                        v[ty.x][ty.y]=ty.step;
                       q.push(ty);
                    }
                }
            }
        }
    }
    if(mins<inff)
    cout<<mins<<endl;
    else cout<<"Poor ANGEL has to stay in the prison all his life.\n";
}
int main()
{
    int i,j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        getchar();
        for(i=0;i<n;i++)
        {
            scanf("%s",mat[i]);
            for(j=0;j<m;j++)
            {
                if(mat[i][j]=='r')
                {
                    stx=i;
                    sty=j;
                }
                if(mat[i][j]=='a')
                {
                    enx=i;
                    eny=j;
                }
            }
        }
        for(i=0;i<=n;i++)
        {
            for(j=0;j<=m;j++)
                v[i][j]=inff;
        }
        mins=inff;
        bfs();
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章