迷宫问题(八方向)
input:
1
6 8
0 1 1 1 0 1 1 1
1 0 1 0 1 0 1 0
0 1 0 0 1 1 1 1
0 1 1 1 0 0 1 1
1 0 0 1 1 0 0 0
0 1 1 0 0 1 1 0
output:
YES
(1,1) (2,2) (3,1) (4,1) (5,2) (5,3) (6,4) (6,5) (5,6) (4,5) (4,6) (5,7) (5,8) (6,8) (递归)
(1,1) (2,2) (3,3) (3,4) (4,5) (5,6) (5,7) (6,8) (栈)
题目要求从(1,1)点走到输入的(6,8)这个点。本题可以用深搜栈(stack)做。
#include<iostream>
#include<stack>
using namespace std;
struct point{
int x;
int y;
};
int **Maze;
int cnt = 0;
stack<point> sp;
point m[8] = { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 }, { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 } };
void Create(int row, int column){
//创建迷宫,注意到用0表示可走,1表示墙,将整个输入的迷宫再用墙围着,处理的时候就不用特别注意边界问题
int i, j;
for (i = 0; i<row + 2; i++)
Maze[i][0] = Maze[i][column + 1] = 1;
for (j = 0; j<column + 2; j++)
Maze[0][j] = Maze[row + 1][j] = 1;
for (i = 1; i <= row; i++){
for (j = 1; j <= column; j++){
cin >> Maze[i][j];
}
}
}
/*
bool MazePath(int row,int column,int x,int y){
//判断是否有路径从入口到出口,保存该路径(递归)
Maze[x][y] = -1;
point temp;
temp.x = x;
temp.y = y;
sp.push(temp);
for(int i=0; i<8; i++){
if(x + move[i].x == row && y + move[i].y == column)return true;
if(Maze[x + move[i].x][y + move[i].y] == 0){
if(MazePath(row,column,x + move[i].x,y + move[i].y))return true;
}
}
sp.pop();
return false;
}
*/
bool MazePath(int row, int column, int x, int y){ //(1,1)为迷宫入口
//判断是否有路径从入口到出口,保存该路径(栈)
stack<point> save;
bool flag;
point now;
now.x = x; //初始化迷宫的入口
now.y = y;
save.push(now);
while (!save.empty()){
now = save.top(); //取栈顶元素
if (Maze[now.x][now.y] == 0){ //如果路可以走
sp.push(now); //因为sp为全局变量所以下面也用得到,画路径要用
Maze[now.x][now.y] = -1;
}
flag = true;
for (int i = 0; i<8; i++){
if (now.x + m[i].x == row && now.y + m[i].y == column)return true; //到达终点.
if (Maze[now.x + m[i].x][now.y + m[i].y] == 0){ //如果道路可通
point temp;
temp.x = now.x + m[i].x;
temp.y = now.y + m[i].y;
save.push(temp);
flag = false;
}
}
if (flag){
save.pop();
sp.pop();
}
}
}
void PrintPath(int row, int column){
//输出从入口到出口的路径
point temp;
temp.x = row;
temp.y = column;
stack<point> pp;
pp.push(temp);
while (!sp.empty()){
temp = sp.top();
sp.pop();
pp.push(temp);
}
while (!pp.empty()){
temp = pp.top();
cout << '(' << temp.x << ',' << temp.y << ')' << ' ';
cnt++;
pp.pop();
}
cout << endl;
cout <<"最短路径为:"<< cnt<<"步"<<endl;
}
int main(){
int t, row, column;
cin >> t;
while (t--){
cin >> row >> column;
Maze = new int*[row + 2];
for (int i = 0; i<row + 2; i++)Maze[i] = new int[column + 2];
Create(row, column);
if (MazePath(row, column, 1, 1)){
cout << "YES" << endl;
PrintPath(row, column);
}
else cout << "NO" << endl;
}
return 0;
}