【BFS】Oliver的救援

问题描述】
  在你的帮助下,Oliver终于追到小X了,可有一天,坏人把小X抓走了。这正是Oliver英雄救美的时候。所以,Oliver又找到哆啦A梦,借了一个机器,机器显示出一幅方格地图,它告诉Oliver哪里能走,哪里不能走,。并且Oliver在这个地图的右下角,而小X在左上角。时间紧急,Oliver想知道,最少要走多少个格子,才能找到小X。(只能直走)。
【输入格式】
  sos.in共N+1行,第一行为N,以下N行N列0-1矩阵,1表示不能通过,0表示可以通过(左上角和右下角为0).
【输出格式】
  sos.out共一个数,为最少的走的格子数.                     
【样例输入】      【样例输出】           
  5                 9
  0 1 1 1 1
  0 0 1 1 1 
  1 0 0 0 1                                  
  1 1 1 0 1
  1 1 1 0 0
【数据范围】
  对于100%的数据,N<30.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <algorithm>

#define loc
#define mxn 30+10
#define mxq 200000

using namespace std;

int n,m;
int mp[mxn][mxn];
bool v[mxn][mxn];

const int mx[5]={0,1,0,-1};
const int my[5]={1,0,-1,0};

struct nd
{
    int x,y;
    int stp;   
}q[mxq];
int l,r;


inline void bfs()
{
    int X,Y;
    l=r=1;
    v[1][1]=true;   
    q[r].x=q[r].y=1,q[r].stp=1;
    
    while (l<=r)
    {
        for (int i=0;i<4;++i)
        {
            X=q[l].x+mx[i],Y=q[l].y+my[i];
            
            if (X==n&&Y==n)
            {
                printf("%d",q[l].stp+1);
                exit(0);          
            }
            
            if (X>=1&&X<=n&&Y>=1&&Y<=n&&!v[X][Y]&&!mp[X][Y])
            {
                r=(r+1)%mxq;
                v[X][Y]=true;
                q[r].x=X,q[r].y=Y;
                q[r].stp=q[l].stp+1;                                                                   
            }
        }  
        
        l=(l+1)%mxq;
    }
}

int main()
{
    #ifdef loc
    freopen("sos.in","r",stdin);
    freopen("sos.out","w",stdout);
    #endif
    
    scanf("%d",&n);
    for (int i=1;i<=n;++i)
    for (int j=1;j<=n;++j) scanf("%d",&mp[i][j]);
    
    bfs();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值