DFS求迷宫问题

/*
迷宫问题(四方向)
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) (栈)
*/
#include<iostream>
#include<stack>
using namespace std;
struct point{
	int x;
	int y;
};
int Maze[10][10];
stack<point> sp;
int dir[4][2] = { { -1, 0 },{ 0, -1 }, { 0, 1 }, { 1, 0 }};
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<4; i++)
	{
		if(x + dir[i].x == row && y + dir[i].y == column)
			return true;
		if(Maze[x + dir[i].x][y + dir[i].y] == 0)
		{
			if(MazePath(row,column,x + dir[i].x,y + dir[i].y))
				return true;
		}
	}
	sp.pop();
	return false;
}
*/
bool MazePath(int row, int column, int x, int y)
{
	//将起始点压入栈,然后根据起始点的上下左右方向是否可行来压入栈,如果四个方向均不可行,那么要弹出栈顶元素
	//sp用来保存路径
	point first;
	stack<point>savepoint;
	first.x = x; first.y = y;
	savepoint.push(first);
	while (!savepoint.empty())
	{
		point curr = savepoint.top();
		sp.push(curr);
		Maze[curr.x][curr.y] = -1;
		bool flag = true;
		for (int i = 0; i < 4; i++)
		{
			int nx = curr.x + dir[i][0];
			int ny = curr.y + dir[i][1];
			if (nx == row && ny == column)
				return true;
			if (Maze[nx][ny] == 0)
			{
				point p;
				p.x = nx; p.y = ny;
				savepoint.push(p);
				flag = false;
			}
		}
		if (flag)
		{
			savepoint.pop();
			sp.pop();
		}
	}
	return false;
}
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 << ')' << ' ';
		pp.pop();
	}
	cout << endl;
}
int main()
{
	freopen("sample_input.txt","r",stdin);
	int t, row, column;
	cin >> t;
	while (t--)
	{
		cin >> row >> column;
		Create(row, column);
		if (MazePath(row, column, 1, 1))
		{
			cout << "YES" << endl;
			PrintPath(row, column);
		}
		else cout << "NO" << endl;
	}
	return 0;
}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/u014338577/article/details/48108983
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞