TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
knight_tour.cpp
Go to the documentation of this file.
1
16
#include <array>
17
#include <iostream>
18
23
namespace
backtracking
{
29
namespace
knight_tour
{
39
template
<
size_t
V>
40
bool
issafe
(
int
x,
int
y,
const
std::array<std::array<int, V>, V> &sol) {
41
return
(x < V && x >= 0 && y < V && y >= 0 && sol[x][y] == -1);
42
}
43
56
template
<
size_t
V>
57
bool
solve
(
int
x,
int
y,
int
mov
, std::array<std::array<int, V>, V> &sol,
58
const
std::array<int, V> &xmov, std::array<int, V> &ymov) {
59
int
k = 0, xnext = 0, ynext = 0;
60
61
if
(
mov
== V * V) {
62
return
true
;
63
}
64
65
for
(k = 0; k < V; k++) {
66
xnext = x + xmov[k];
67
ynext = y + ymov[k];
68
69
if
(
issafe<V>
(xnext, ynext, sol)) {
70
sol[xnext][ynext] =
mov
;
71
72
if
(
solve<V>
(xnext, ynext,
mov
+ 1, sol, xmov, ymov) ==
true
) {
73
return
true
;
74
}
else
{
75
sol[xnext][ynext] = -1;
76
}
77
}
78
}
79
return
false
;
80
}
81
}
// namespace knight_tour
82
}
// namespace backtracking
83
88
int
main
() {
89
const
int
n = 8;
90
std::array<std::array<int, n>, n> sol = {0};
91
92
int
i = 0, j = 0;
93
for
(i = 0; i < n; i++) {
94
for
(j = 0; j < n; j++) {
95
sol[i][j] = -1;
96
}
97
}
98
99
std::array<int, n> xmov = {2, 1, -1, -2, -2, -1, 1, 2};
100
std::array<int, n> ymov = {1, 2, 2, 1, -1, -2, -2, -1};
101
102
sol[0][0] = 0;
103
104
bool
flag =
backtracking::knight_tour::solve<n>
(0, 0, 1, sol, xmov, ymov);
105
if
(flag ==
false
) {
106
std::cout <<
"Error: Solution does not exist\n"
;
107
}
else
{
108
for
(i = 0; i < n; i++) {
109
for
(j = 0; j < n; j++) {
110
std::cout << sol[i][j] <<
" "
;
111
}
112
std::cout <<
"\n"
;
113
}
114
}
115
return
0;
116
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
backtracking::knight_tour::solve
bool solve(int x, int y, int mov, std::array< std::array< int, V >, V > &sol, const std::array< int, V > &xmov, std::array< int, V > &ymov)
Definition
knight_tour.cpp:57
backtracking::knight_tour::issafe
bool issafe(int x, int y, const std::array< std::array< int, V >, V > &sol)
Definition
knight_tour.cpp:40
backtracking
for vector container
knight_tour
Functions for the Knight's tour algorithm.
mov
void mov(tower *From, tower *To)
Definition
tower_of_hanoi.cpp:39
backtracking
knight_tour.cpp
Generated by
1.18.0