Rat in a Maze 回溯法解迷宫

眉间皱痕 提交于 2019-11-28 09:50:49

一个迷宫被给出为n*n二进制矩阵的块,其中源块是最左上方的块,即Maze[0][0],目标块是最右下方的块,即Maze[n-1][n-1]。老鼠从源头出发,必须到达目的地。老鼠只能朝两个方向移动:向前和向下。

在迷宫矩阵中,0表示块是死端,1表示块可以用于从源到目标的路径。请注意,这是典型迷宫问题的简单版本。例如,更复杂的版本可能是老鼠可以向四个方向移动,而更复杂的版本可能移动的次数有限。

下面是一个迷宫的例子。

 

Backtracking 回溯法的三部曲:

1 初始化原始数据,开始点

2 判断下一步是否合法,如果合法就继续递归搜索答案,如果不合法就返回

3 递归直到找到答案,返回真值

这里只需要找到一个解就可以,所以只要找到一个解就可以马上返回。

/*
A Maze is given as N*N binary matrix of blocks where source block is the upper
left most block i.e., maze[0][0] and destination block is lower rightmost
block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination.
The rat can move only in two directions: forward and down. In the maze matrix,
0 means the block is dead end and 1 means the block can be used in the path
from source to destination.
*/
#include <iostream>
#define size 4
using namespace std;
int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size])
{
	if ((currposrow == size - 1) && (currposcol == size - 1))
	{
		soln[currposrow][currposcol] = 1;
		for (int i = 0; i<size; ++i)
		{
			for (int j = 0; j<size; ++j)
			{
				cout << soln[i][j];
			}
			cout << endl;
		}
		return 1;
	}
	else
	{
		soln[currposrow][currposcol] = 1;

		// if there exist a solution by moving one step ahead in a collumn
		if ((currposcol<size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln))
		{
			return 1;
		}

		// if there exists a solution by moving one step ahead in a row
		if ((currposrow<size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln))
		{
			return 1;
		}

		// the backtracking part
		soln[currposrow][currposcol] = 0;
		return 0;
	}
}

int main(int argc, char const *argv[])
{
	int maze[size][size] = {
		{ 1, 0, 1, 0 },
		{ 1, 0, 1, 1 },
		{ 1, 0, 0, 1 },
		{ 1, 1, 1, 1 }
	};

	int soln[size][size];

	for (int i = 0; i<size; ++i)
	{
		for (int j = 0; j<size; ++j)
		{
			soln[i][j] = 0;
		}
	}

	int currposrow = 0;
	int currposcol = 0;
	solveMaze(currposrow, currposcol, maze, soln);
	system("pause");
	return 0;
}

  

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!