问题描述】 在你的帮助下,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; }
【BFS】Oliver的救援
最新推荐文章于 2019-12-07 15:10:23 发布