-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathrat_in_maze.cpp
87 lines (77 loc) · 2.51 KB
/
rat_in_maze.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <array>
#include <iostream>
#include <cassert>
namespace backtracking
{
namespace rat_maze
{
template <size_t size>
bool solveMaze(int currposrow, int currposcol,
const std::array<std::array<int, size>, size> &maze,
std::array<std::array<int, size>, size> soln)
{
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)
{
std::cout << soln[i][j] << " ";
}
std::cout << std::endl;
}
return true;
}
else
{
soln[currposrow][currposcol] = 1;
// jika ada solusi dengan bergerak satu langkah di depan dalam kolom
if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 &&
solveMaze(currposrow, currposcol + 1, maze, soln))
{
return true;
}
// jika ada solusi dengan bergerak satu langkah ke depan berturut-turut
if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 &&
solveMaze(currposrow + 1, currposcol, maze, soln))
{
return true;
}
// backtracking
soln[currposrow][currposcol] = 0;
return false;
}
}
} // namespace rat_maze
} // namespace backtracking
/**
* @brief Test
* @returns void
*/
static void test()
{
const int size = 4;
std::array<std::array<int, size>, size> maze = {
std::array<int, size>{1, 0, 1, 0}, std::array<int, size>{1, 0, 1, 1},
std::array<int, size>{1, 0, 0, 1}, std::array<int, size>{1, 1, 1, 1}};
std::array<std::array<int, size>, size> soln{};
// Backtracking: atur solusi matriks ke nol
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
soln[i][j] = 0;
}
}
int currposrow = 0; // Posisi saat ini dalam baris
int currposcol = 0; // Posisi saat ini dalam kolom
assert(backtracking::rat_maze::solveMaze<size>(currposrow, currposcol, maze,
soln) == 1);
}
int main()
{
// jalankan test
test();
return 0;
}