题目描述 给出一个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结尾,具体格式参考示范数据
输出的代码参考如下:
//path是保存路径的堆栈,堆栈中每个元素都包含x坐标和y坐标,用属性xp和yp表示
//path1是一个临时堆栈,把path的数据倒序输出到path1,使得路径按正序输出
if (!path.empty()) //找到路径
{ //......若干代码,实现path的数据导入path1
i=0; //以下是输出路径的代码
while (!path1.empty())
{ cpos = path1.top();
if ( (++i)%4 == 0 )
cout<<'['<<cpos.xp<<','<<cpos.yp<<']'<<"--"<<endl;
else
cout<<'['<<cpos.xp<<','<<cpos.yp<<']'<<"--";
path1.pop();
}
cout<<"END"<<endl;
}
else
cout<<"no path"<<endl; //找不到路径输出no path
样例输入 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
样例输出
[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>
#include <string>
using namespace std;
struct position {
int x,y;
};
int main() {
int t, n;
cin>>t;
while(t--) {
stack<position> path;
cin>>n;
int **maze = new int*[n];
for(int i = 0; i < n; i++) {
maze[i] = new int [n];
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cin>>maze[i][j];
}
}
path.push({0,0});
maze[0][0] = 1;
int i = 0, j = 0;
while(1) { //右下左上
if(j + 1 < n && maze[i][j+1] == 0) { //右走
maze[i][j+1] = 1;
path.push({i,++j});
} else if(i + 1 < n && maze[i+1][j] == 0) { // 下走
maze[i+1][j] = 1;
path.push({++i,j});
} else if(j - 1 >= 0 && maze[i][j-1] == 0) { //左走
maze[i][j-1] = 1;
path.push({i,--j});
} else if(i - 1 >= 0 && maze[i-1][j] == 0) { //上走
maze[i-1][j] = 1;
path.push({--i,j});
} else {
path.pop();
if(!path.empty()) { //无路可走回到原点时,path为空,防止越界
i = path.top().x;
j = path.top().y;
}
}
if(path.empty() || (i == n - 1 && j == n - 1)) { //判断是否在到达终点或返回起点
break;
}
}
if(path.empty()) {
cout<<"no path"<<endl;
} else {
stack<position> path1;
while(!path.empty()) {
path1.push(path.top());
path.pop();
}
i = 0;
while (!path1.empty()) {
if ((++i) % 4 == 0) {
cout << '[' << path1.top().x << ',' << path1.top().y << ']' << "--" << endl;
} else {
cout << '[' << path1.top().x << ',' << path1.top().y << ']' << "--";
}
path1.pop();
}
cout << "END" << endl;
}
for (int i = 0; i < n; i++)
delete []maze[i];
delete[]maze;
}
}