TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
rat_maze.cpp
Go to the documentation of this file.
1
18
19
#include <array>
20
#include <cassert>
21
#include <iostream>
22
27
namespace
backtracking
{
34
namespace
rat_maze
{
46
template
<
size_t
size>
47
bool
solveMaze
(
int
currposrow,
int
currposcol,
48
const
std::array<std::array<int, size>, size> &maze,
49
std::array<std::array<int, size>, size> soln) {
50
if
((currposrow == size - 1) && (currposcol == size - 1)) {
51
soln[currposrow][currposcol] = 1;
52
for
(
int
i = 0; i < size; ++i) {
53
for
(
int
j = 0; j < size; ++j) {
54
std::cout << soln[i][j] <<
" "
;
55
}
56
std::cout << std::endl;
57
}
58
return
true
;
59
}
else
{
60
soln[currposrow][currposcol] = 1;
61
62
// if there exist a solution by moving one step ahead in a column
63
if
((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 &&
64
solveMaze
(currposrow, currposcol + 1, maze, soln)) {
65
return
true
;
66
}
67
68
// if there exists a solution by moving one step ahead in a row
69
if
((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 &&
70
solveMaze
(currposrow + 1, currposcol, maze, soln)) {
71
return
true
;
72
}
73
74
// the backtracking part
75
soln[currposrow][currposcol] = 0;
76
return
false
;
77
}
78
}
79
}
// namespace rat_maze
80
}
// namespace backtracking
81
86
static
void
test
() {
87
const
int
size = 4;
88
std::array<std::array<int, size>, size> maze = {
89
std::array<int, size>{1, 0, 1, 0}, std::array<int, size>{1, 0, 1, 1},
90
std::array<int, size>{1, 0, 0, 1}, std::array<int, size>{1, 1, 1, 1}};
91
92
std::array<std::array<int, size>, size> soln{};
93
94
// Backtracking: setup matrix solution to zero
95
for
(
int
i = 0; i < size; ++i) {
96
for
(
int
j = 0; j < size; ++j) {
97
soln[i][j] = 0;
98
}
99
}
100
101
int
currposrow = 0;
// Current position in the rows
102
int
currposcol = 0;
// Current position in the columns
103
104
assert(
backtracking::rat_maze::solveMaze<size>
(currposrow, currposcol, maze,
105
soln) == 1);
106
}
107
112
int
main
() {
113
test
();
// run self-test implementations
114
return
0;
115
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
backtracking
for vector container
rat_maze
Functions for Rat in a Maze algorithm.
backtracking::rat_maze::solveMaze
bool solveMaze(int currposrow, int currposcol, const std::array< std::array< int, size >, size > &maze, std::array< std::array< int, size >, size > soln)
Solve rat maze problem.
Definition
rat_maze.cpp:47
backtracking
rat_maze.cpp
Generated by
1.18.0