TheAlgorithms-C-Plus-Plus/backtracking/rat_maze.cpp

74 lines
1.7 KiB
C++
Raw Normal View History

2018-03-13 07:06:21 +08:00
/*
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;
2019-08-21 10:10:08 +08:00
int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size])
2018-03-13 07:06:21 +08:00
{
2019-08-21 10:10:08 +08:00
if ((currposrow == size - 1) && (currposcol == size - 1))
2018-03-13 07:06:21 +08:00
{
2019-08-21 10:10:08 +08:00
soln[currposrow][currposcol] = 1;
for (int i = 0; i < size; ++i)
2018-03-13 07:06:21 +08:00
{
2019-08-21 10:10:08 +08:00
for (int j = 0; j < size; ++j)
2018-03-13 07:06:21 +08:00
{
2019-08-21 10:10:08 +08:00
cout << soln[i][j];
2018-03-13 07:06:21 +08:00
}
2019-08-21 10:10:08 +08:00
cout << endl;
2018-03-13 07:06:21 +08:00
}
return 1;
}
else
{
2019-08-21 10:10:08 +08:00
soln[currposrow][currposcol] = 1;
2018-03-13 07:06:21 +08:00
// if there exist a solution by moving one step ahead in a collumn
2019-08-21 10:10:08 +08:00
if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln))
2018-03-13 07:06:21 +08:00
{
return 1;
}
// if there exists a solution by moving one step ahead in a row
2019-08-21 10:10:08 +08:00
if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln))
2018-03-13 07:06:21 +08:00
{
return 1;
}
// the backtracking part
2019-08-21 10:10:08 +08:00
soln[currposrow][currposcol] = 0;
2018-03-13 07:06:21 +08:00
return 0;
}
}
int main(int argc, char const *argv[])
{
2019-08-21 10:10:08 +08:00
int maze[size][size] = {
{1, 0, 1, 0},
{1, 0, 1, 1},
{1, 0, 0, 1},
{1, 1, 1, 1}};
2018-03-13 07:06:21 +08:00
int soln[size][size];
2019-08-21 10:10:08 +08:00
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
2018-03-13 07:06:21 +08:00
{
2019-08-21 10:10:08 +08:00
soln[i][j] = 0;
2018-03-13 07:06:21 +08:00
}
2019-08-21 10:10:08 +08:00
}
2018-03-13 07:06:21 +08:00
2019-08-21 10:10:08 +08:00
int currposrow = 0;
int currposcol = 0;
solveMaze(currposrow, currposcol, maze, soln);
2018-03-13 07:06:21 +08:00
return 0;
}