1. 程式人生 > >1254:走出迷宮

1254:走出迷宮

style 最短 set 保存 遍歷 ring nbsp cst -s

背景眾所周知,這道題還是個迷宮板子。。。。。

原理:廣搜,檢索路徑,將走過的和墻所在區域置為0,其他區域置為1(可以走)。那麽,用隊列存一下路徑,搜索每深一層,步數++,然後後退時步數再-回去就行了,最後遍歷完,將所有的路徑步數比對(或者設置minn,保存歷史搜索最短步數就行了)很簡單啊。

用到QUEUE

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int r,c;
int X[4]={0,1,0,-1},
    Y[4]={1,0,-1
,0}; bool a[200][200]; int main() { queue<int> x,y,b,f; int n,m; b.push(0);f.push(4); scanf("%d%d",&r,&c); memset(a,0,sizeof(a)); for(int i=1;i<=r;++i) { char C; scanf("%c",&C);//去掉前面的空格 for(int j=1;j<=c;++j) { scanf(
"%c",&C); if(C==#) a[i][j]=1; else if(C==S) {x.push(i);y.push(j);} else if(C==T) {n=i;m=j;} } } //printf("%d %d\n%d %d\n",x.front(),y.front(),n,m); do { for(int i=0;i<4;++i) if(f.front()!=(i+2
)%4) { int xx=x.front()+X[i],yy=y.front()+Y[i]; if(!a[xx][yy]&&xx>=1&&xx<=r&&yy>=1&&yy<=c) { b.push(b.front()+1); x.push(xx);y.push(yy); a[xx][yy]=1;f.push(i); if(xx==n&&yy==m) { printf("%d",b.back()); return 0; } } } x.pop();y.pop(); b.pop();f.pop(); } while(!x.empty()); return 0; }

1254:走出迷宮