TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
knight_tour.cpp
Go to the documentation of this file.
1
16#include <array>
17#include <iostream>
18
23namespace backtracking {
29namespace knight_tour {
39template <size_t V>
40bool 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
56template <size_t V>
57bool 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
88int 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}
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)
int main()
Main function.
bool issafe(int x, int y, const std::array< std::array< int, V >, V > &sol)
for vector container
Functions for the Knight's tour algorithm.
void mov(tower *From, tower *To)