简单BFS ZOJ 1649 Rescue

本文使用BFS算法解决迷宫问题,通过标记每个点的最短路径时间,优化求解过程。详细介绍了算法实现步骤及应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值