TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
rat_maze.cpp
Go to the documentation of this file.
1
19#include <array>
20#include <cassert>
21#include <iostream>
22
27namespace backtracking {
34namespace rat_maze {
46template <size_t size>
47bool 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
86static 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
112int main() {
113 test(); // run self-test implementations
114 return 0;
115}
for vector container
Functions for Rat in a Maze algorithm.
static void test()
Self-test implementations.
Definition rat_maze.cpp:86
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
int main()
Main function.
Definition rat_maze.cpp:112