题目描述
给出一个N*N的迷宫矩阵示意图,从起点[0,0]出发,寻找路径到达终点[N-1, N-1]
要求使用堆栈对象来实现,具体算法参考课本3.2.4节51页
输入
第一行输入t,表示有t个迷宫
第二行输入n,表示第一个迷宫有n行n列
第三行起,输入迷宫每一行的每个方格的状态,0表示可通过,1表示不可通过
输入n行
以此类推输入下一个迷宫
输出
逐个输出迷宫的路径
如果迷宫不存在路径,则输出no path并回车
如果迷宫存在路径,将路径中每个方格的x和y坐标输出,从起点到终点,每输出四个方格就换行,最终以单词END结尾,具体格式参考示范数据
输入样例1
2
8
0 0 0 1 1 1 1 1
1 0 0 0 1 0 0 1
1 0 0 0 1 0 0 0
1 1 0 0 0 0 0 1
0 0 1 1 0 1 1 0
0 0 0 0 0 0 1 1
1 1 1 1 1 0 0 1
0 0 0 0 1 0 0 0
7
0 0 0 1 1 1 1
1 0 0 1 0 0 1
1 0 0 1 0 0 0
1 1 0 0 0 0 1
0 0 1 1 0 1 0
1 0 0 0 0 1 0
0 0 0 0 1 1 0
输出样例1
[0,0]--[0,1]--[0,2]--[1,2]--
[1,3]--[2,3]--[3,3]--[3,4]--
[4,4]--[5,4]--[5,5]--[6,5]--
[6,6]--[7,6]--[7,7]--END
no path
#include <iostream>
#include <stack>
using namespace std;
struct Location
{
int x;
int y;
};
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int** map = new int* [n];
for (int i = 0; i < n; i++)
map[i] = new int[n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cin >> map[i][j];
}
stack<Location> path;
Location now;
now.x = 0;
now.y = 0;
path.push(now);
map[0][0] = 1;
while (!path.empty())
{
if (now.x == n - 1 && now.y == n - 1)
break;
if (now.y + 1 < n && map[now.x][now.y + 1] == 0)
{
now.y++;
map[now.x][now.y] = 1;
path.push(now);
}
else if (now.x + 1 < n && map[now.x + 1][now.y] == 0)
{
now.x++;
map[now.x][now.y] = 1;
path.push(now);
}
else if (now.y - 1 >= 0 && map[now.x][now.y - 1] == 0)
{
now.y--;
map[now.x][now.y] = 1;
path.push(now);
}
else if (now.x - 1 >= 0 && map[now.x - 1][now.y] == 0)
{
now.x--;
map[now.x][now.y] = 1;
path.push(now);
}
else
{
path.pop();
if (path.empty())
break;
now = path.top();
}
}
if (path.empty())
cout << "no path" << endl;
else
{
stack<Location> res;
int num = path.size();
for (int i = 0; i < num; i++)
{
res.push(path.top());
path.pop();
}
for (int i = 0; i < num; i++)
{
cout << "[" << res.top().x << "," << res.top().y << "]--";
if (i == num - 1)
{
cout << "END" << endl;
break;
}
if ((i + 1) % 4 == 0)
cout << endl;
res.pop();
}
}
for (int i = 0; i < n; i++)
delete[]map[i];
delete[]map;
}
return 0;
}