1. 程式人生 > >NOI題庫2.5 6264 走出迷宮

NOI題庫2.5 6264 走出迷宮

描述
當你站在一個迷宮裡的時候,往往會被錯綜複雜的道路弄得失去方向感,如果你能得到迷宮地圖,事情就會變得非常簡單。
假設你已經得到了一個n*m的迷宮的圖紙,請你找出從起點到出口的最短路。
輸入
第一行是兩個整數n和m(1<=n,m<=100),表示迷宮的行數和列數。
接下來n行,每行一個長為m的字串,表示整個迷宮的佈局。字元’.’表示空地,’#’表示牆,’S’表示起點,’T’表示出口。
輸出
輸出從起點到出口最少需要走的步數。
樣例輸入
3 3
S#T
.#.

樣例輸出
6

一個裸廣度優先搜尋(BFS),用C++STL裡的queue容器即可輕鬆實現
NOI題庫再現水題,喜大普奔,RP++

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int N=105,tx[4]={0,1,0,-1},ty[4]={1,0,-1,0};
bool a[N][N];
struct node
{
    int x,y,s;
}k;
queue<node>q;
int main()
{
    cin.sync_with_stdio(false);
    int n,m,sta_x,sta_y,end_x,end_y,qx,qy,qs,i,j,l;
    char
c; bool flag; cin>>n>>m; for(i=1;i<=n;i++) for(j=1;j<=n;j++) { cin>>c; if(c=='#') a[i][j]=true; if(c=='S') sta_x=i,sta_y=j; if(c=='T') end_x=i,end_y=j; } k.x=sta_x; k.y=sta_y; k.s=0
; q.push(k); a[sta_x][sta_y]=true; flag=false; while(!q.empty()) { for(l=0;l<4;l++) { k=q.front(); qx=k.x+tx[l]; qy=k.y+ty[l]; qs=k.s; if(qx<1||qx>n||qy<1||qy>m) continue; if(a[qx][qy]==false) { a[qx][qy]=true; k.x=qx; k.y=qy; k.s=qs+1; q.push(k); } if(qx==end_x&&qy==end_y) { flag=true; break; } } if(flag==true) break; q.pop(); } k=q.back(); cout<<k.s; return 0; }