题目描述
给出一个N*N的迷宫矩阵示意图,从起点[0,0]出发,寻找路径到达终点[N-1, N-1]
要求使用堆栈对象来实现,具体算法参考课本3.2.4节51页
输入
第一行输入t,表示有t个迷宫
第二行输入n,表示第一个迷宫有n行n列
第三行起,输入迷宫每一行的每个方格的状态,0表示可通过,1表示不可通过
输入n行
以此类推输入下一个迷宫
输出
逐个输出迷宫的路径
如果迷宫不存在路径,则输出无路径并回车
如果迷宫存在路径,将路径中每个方格的x和y坐标输出,从起点到终点,每输出四个方格就换行,最终以单词END结尾,具体格式参考示范数据
输出的代码参考如下:
path是保存路径的堆栈,堆栈中每个元素都包含x坐标和y坐标,用属性xp和yp表示
path1是一个临时堆栈,把path的数据倒序输出到path1,使得路径按正序输出
if (!path.empty()) //找到路径
{ //......若干代码,实现path的数据导入path1
i=0;以下是输出路径的代码
而 (!path1.empty())
{ CPOS = path1.top();
if ( (++i)%4 == 0 )
cout<<'['<<cpos.xp<<','<<cpos.yp<<']'<<“--”<<endl;
还
cout<<'['<<cpos.xp<<','<<cpos.yp<<']'<<“--”;
path1.pop();
}
cout<<“END”<<endl;
}
还
cout<<“no path”<<endl;找不到路径输出无路径
输入样例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<cstring>
#include<stack>
using namespace std;
struct Position{
int x;
int y;
};
int main(){
int t,m;
cin>>t;
while(t--){
cin>>m;
stack<Position>path1;//操作栈
int **mg=new int *[m];
for(int i=0;i<m;i++){
mg[i]=new int[m];
}
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
cin>>mg[i][j];
}
}//把迷宫输入
if(mg[0][0]==1){
cout<<"no path"<<endl;
}else{
path1.push({0,0});
mg[0][0]=1;
int i=0,j=0;
while(1){//右下左上
if(j+1<m&&mg[i][j+1]==0){
mg[i][j+1]=1;
path1.push({i,++j});
//mg[i][++j]=1;
}else if(i+1<m&&mg[i+1][j]==0){
mg[i+1][j]=1;
path1.push({++i,j});
//mg[i+1][j]=1;
}else if(j-1>=0&&mg[i][j-1]==0){
mg[i][j-1]=1;
path1.push({i,--j});
//mg[i][j-1]=1;
} else if(i-1>=0&&mg[i-1][j]==0){
mg[i-1][j]=1;
path1.push({--i,j});
//mg[i-1][j]=1;
}else{
path1.pop();
if(!path1.empty()){
i=path1.top().x;
j=path1.top().y;
}
}
if(path1.empty()||(i==m-1&&j==m-1)){
break;
}//空或者到达终点时
}
if(path1.empty()){
cout<<"no path"<<endl;
}else{
stack<Position>path;//输出栈
while(!path1.empty()){
path.push(path1.top());
path1.pop();
}
i=0;
while(!path.empty()){
if((++i)%4==0){
cout<<"["<<path.top().x<<","<<path.top().y<<"]"<<"--"<<endl;
}else{
cout<<"["<<path.top().x<<","<<path.top().y<<"]"<<"--";
}
path.pop();
}
cout<<"END"<<endl;
}
}
}
return 0;
}