该题为水题,代码如下:
- /*
- ID: millky
- PROG: maze1
- LANG: C++
- */
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cmath>
- #include <cstdio>
- #include <algorithm>
- #include <vector>
- #include<iomanip>
- using namespace std;
- #define sqare(x) (x)*(x)
- struct pt
- {
- bool l,r,u,b;
- pt(){l=r=u=b=false;}
- };
- struct haha
- {
- int pt,step;
- };
- char ormp[210][100];
- pt mps[4000];
- bool visited[4000];
- int ans[4000];
- haha fbfs[4000];
- int head,tail,longest=0;
- int m,n,ns;
- vector<int> holes;
- void buildMap()
- {
- for (int i=1,lim=2*m+1;i<lim;i+=2)
- for (int j=1,haha=2*n+1;j<haha;j+=2)
- {
- if(ormp[i-1][j]==' ') mps[ns].u=true;
- if(ormp[i+1][j]==' ') mps[ns].b=true;
- if(ormp[i][j-1]==' ') mps[ns].l=true;
- if(ormp[i][j+1]==' ') mps[ns].r=true;
- ++ns;
- }
- for (int i=1,j=2*m,lim=2*n+1;i<lim;i+=2){
- if(ormp[0][i] == ' ') holes.push_back(i>>1);
- if(ormp[j][i] == ' ') holes.push_back(n*(m-1)+i/2);
- }
- for (int i=1,j=2*n,lim=2*m+1;i<lim;i+=2)
- {
- if(ormp[i][0] == ' ') holes.push_back(n*(i/2));
- if(ormp[i][j] == ' ') holes.push_back(n*(i/2+1)-1);
- }
- }
- int bfs(int exit)
- {
- ans[exit]=1;
- int maxL=0,cur,temp;
- for (int i=0;i<ns;++i) visited[i]=false;
- visited[exit]=true; head=0;tail=1;fbfs[0].pt=exit;fbfs[0].step=1;
- while (head<tail)
- {
- maxL = fbfs[head].step+1; cur=fbfs[head++].pt;
- temp=cur-n;
- if (mps[cur].u && cur>=n && !visited[temp])
- {
- visited[temp]=true;
- fbfs[tail].pt=cur-n;
- fbfs[tail].step=maxL;
- ++tail;
- ans[temp]=min(ans[temp],maxL);
- }
- temp=cur+n;
- if (temp<ns && !visited[temp] && mps[cur].b)
- {
- visited[temp]=true;
- fbfs[tail].pt=temp;
- fbfs[tail].step=maxL;
- ++tail;
- ans[temp]=min(ans[temp],maxL);
- }
- temp=cur+1;
- if (temp%n && !visited[temp] && mps[cur].r)
- {
- visited[temp]=true;
- fbfs[tail].pt=temp;
- fbfs[tail].step=maxL;
- ++tail;
- ans[temp]=min(ans[temp],maxL);
- }
- temp=cur-1;
- if (mps[cur].l && cur%n && !visited[temp])
- {
- visited[temp]=true;
- fbfs[tail].pt=temp;
- fbfs[tail].step=maxL;
- ++tail;
- ans[temp]=min(ans[temp],maxL);
- }
- }
- return fbfs[tail-1].step;
- }
- int main()
- {
- int a;
- freopen("maze1.in","r",stdin);
- freopen("maze1.out","w",stdout);
- scanf("%d%d",&n,&m);
- a=m*2+1;
- getchar();
- for (int i=0;i<a;++i) gets(ormp[i]);
- buildMap();
- a=0;
- for (int i=0;i<ns;++i) ans[i]=100000;
- for (int i=0;i<holes.size();++i)
- bfs(holes[i]);
- for (int i=0;i<ns;++i) if(ans[i]<100000) a=max(a,ans[i]);
- printf("%d/n",a);
- return 0;
- }
本文介绍了一个迷宫寻路算法的实现细节,通过构建迷宫地图并使用广度优先搜索找到从不同入口到迷宫内各点的最短路径。代码采用C++编写,展示了如何定义迷宫结构、进行地图构建及遍历。
296

被折叠的 条评论
为什么被折叠?



