問題描述】 在你的協助下,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;}