【BFS】Oliver的救援_struct

來源:互聯網
上載者:User
問題描述】  在你的協助下,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 200000using 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.