Rat in a Maze backtracking maze solution

Labyrinth is given as a block of n * n binary matrix, wherein the source block is the top left block, i.e. Maze [0] [0], the target block is the lower right block, i.e. Maze [n-1] [ n-1]. Mouse departure from the source, must arrive at the destination. Mouse only move in two directions: forward and downward.

Matrix in the maze, the dead end of a block 0, block 1 may be used to represent the path from source to destination. Please note that this is a simple version of a typical maze problem. For example, a more complex version of the mouse may be movable in four directions, and the limited number of the more complex versions may move.

The following is an example of a maze.

 

Backtracking Backtracking trilogy:

1 initialize the raw data, the starting point

2 to determine the next step is legal, legitimate if it continues recursively search for answers, if not legally return

3 recursively until you find the answer returns a true value

Here just need to find a solution on it, so long as a solution is found can be returned immediately.

/*
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;
}

  

 

Guess you like

Origin www.cnblogs.com/277223178dudu/p/11403721.html