forked from MohmedIkram/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RatInMaze.cpp
65 lines (64 loc) · 1.92 KB
/
RatInMaze.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Note: Rat in a Maze
// Initialisation of solution 2D array
// The code developed in the video may not work on your local IDE. This happens because the
// solution 2D array is not initialized with default value, before making recursive calls. Hence,
// to resolve it, please initialize the 2D-array, before initiating the recursive calls. The following
// code helps you understand where the initialization of solution 2D array has to be done:
// Complete code with initialisation of solution 2D array:
void ratInAMaze(int maze[][20], int n)
{
int **solution = new int *[n];
for (int i = 0; i < n; i++)
{
solution[i] = new int[n];
}
// initialization of solution 2D arrays goes here.
mazeHelp(maze, n, solution, 0, 0);
}
#include <bits/stdc++.h>
using namespace std;
void printSolution(int **solution, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << solution[i][j] << " ";
}
}
cout << endl;
}
void mazeHelp(int maze[][20], int n, int **solution, int x, int y)
{
2 if (x == n - 1 && y == n - 1)
{
solution[x][y] = 1;
printSolution(solution, n);
solution[x][y] = 0;
return;
}
if (x >= n || x < 0 || y >= n || y < 0 || maze[x][y] == 0 || solution[x][y] == 1)
{
return;
}
solution[x][y] = 1;
mazeHelp(maze, n, solution, x - 1, y);
mazeHelp(maze, n, solution, x + 1, y);
mazeHelp(maze, n, solution, x, y - 1);
mazeHelp(maze, n, solution, x, y + 1);
solution[x][y] = 0;
}
void ratInAMaze(int maze[][20], int n)
{
int **solution = new int *[n];
for (int i = 0; i < n; i++)
{
solution[i] = new int[n];
}
// Initialization of solution 2D array with 0
for (int i = 0; i < n; i++)
{
memset(solution[i], 0, n * sizeof(int));
}
mazeHelp(maze, n, solution, 0, 0);
}