题目
任务:可以输入一个任意大小的迷宫数据,用非递归的方法求出一条走出迷宫的路径,并将路径输出;
要求:在上交资料中请写明:存储结构、基本算法(可以使用程序流程图)、源程序、测试数据和结果、算法的时间复杂度、另外可以提出算法的改进方法;
代码
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N];
int d[N][N];
PII path[N][N];
int n, m;
void bfs();
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
bfs();
if (d[n - 1][m - 1] == -1)
cout << "The map has no solution" << endl;
else
{
cout<<"The solution to the map is : "<<endl;
int x = n - 1, y = m - 1;
while (x || y)
{
cout <<" "<< x << " " << y << endl;
auto t = path[x][y];
x = t.first;
y = t.second;
}
cout<<"The length of this path is : ";
cout << d[n - 1][m - 1];
}
return 0;
}
void bfs()
{
queue<PII> vis;
memset(d, -1, sizeof(d));
d[0][0] = 0;
vis.push({0, 0});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (!vis.empty())
{
auto t = vis.front();
vis.pop();
for (int i = 0; i < 4; i++)
{
int x = t.first + dx[i], y = t.second + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
path[x][y] = t;
vis.push({x, y});
}
}
}
}