题目是https://blog.youkuaiyun.com/lesileqin/article/details/89069682 这篇博客的题目。我就不在这里写了,字太多、懒得打了。
就是一个简单的迷宫、输出最短路径。
解题思路:
用一个二维pair数组来存储走出迷宫的路径,数组的下标是对应每个点的下标,对应的内容是其父亲结点的位置,在深搜的过程中,只需要把父亲结点记录上、到最后找到终点、直接输出就好啦!!
代码如下:
#include<iostream>
#include<queue>
#include<stack>
#define MAXN 101
using namespace std;
typedef pair<int,int> loc; //记录坐标
char map[MAXN][MAXN];
int n,m;
int sx,sy,ex,ey;
bool book[MAXN][MAXN]={false};
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
queue<loc> que;
loc path[MAXN][MAXN]; //存储路径
//存储父亲结点的位置
void input()
{
cin >> n >> m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin >> map[i][j];
if(map[i][j]=='S')
sx=i,sy=j;
if(map[i][j]=='G')
ex=i,ey=j;
}
}
void output()
{
int x=ex,y=ey;
int i=0;
int num[MAXN+MAXN][2];
while(1)
{
int k=x;
x=path[x][y].first;
y=path[k][y].second;
num[i][0]=x;
num[i][1]=y;
i++;
if(x==sx&&y==sy)
break;
}
cout << "******************************\n";
for(int j=i-2;j>=0;j--)
cout << "(" << num[j][0]+1 << " , " << num[j][1]+1 << ")\n";
cout << "(" << ex+1 << " , " << ey+1 << ")\n";
cout << i << endl;
}
void bfs()
{
bool flag=false;
loc p,p1;
p.first=sx,p.second=sy;
book[sx][sy]=true;
for(int i=0;i<MAXN;i++)
for(int j=0;j<MAXN;j++)
path[i][j].first=0,path[i][j].second=0;
path[sx][sy].first=sx;
path[sx][sy].second=sy;
que.push(p);
while(!que.empty())
{
p=que.front();
que.pop();
for(int i=0;i<4;i++)
{
int gx=p.first+next[i][0];
int gy=p.second+next[i][1];
if(gx<0||gx>n-1||gy<0||gy>m-1||book[gx][gy]||map[gx][gy]=='#')
continue;
book[gx][gy]=true;
// gx\gy入队
p1.first=gx,p1.second=gy;
path[gx][gy].first=p.first; //记录父亲结点
path[gx][gy].second=p.second;
que.push(p1);
if(gx==ex&&gy==ey)
{
flag=true;
break;
}
}
if(flag)
break;
}
}
int main()
{
input();
bfs();
output();
return 0;
}
/*
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
.........G
.####.###.
....#....#
*/