-
Notifications
You must be signed in to change notification settings - Fork 492
/
TheKnight’stourproblem.cpp
45 lines (41 loc) · 1.33 KB
/
TheKnight’stourproblem.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
#include<bits/stdc++.h>
using namespace std;
//https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
//function to display the 2-d array
void display(vector<vector<int>>& chess) {
for (int i = 0; i < chess.size(); i++) {
for (int j = 0; j < chess.size(); j++) {
cout << chess[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void printKnightsTour(vector<vector<int>>& chess, int n, int r, int c, int upcomingMove) {
//base case
if (r < 0 || c < 0 || r >= n || c >= n || chess[r][c] != 0) {
return;
}
if (upcomingMove == n * n) {
chess[r][c] = upcomingMove;
display(chess);
chess[r][c] = 0;
return;
}
chess[r][c] = upcomingMove;
printKnightsTour(chess, n, r - 2, c + 1, upcomingMove + 1);
printKnightsTour(chess, n, r - 1, c + 2, upcomingMove + 1);
printKnightsTour(chess, n, r + 1, c + 2, upcomingMove + 1);
printKnightsTour(chess, n, r + 2, c + 1, upcomingMove + 1);
printKnightsTour(chess, n, r + 2, c - 1, upcomingMove + 1);
printKnightsTour(chess, n, r + 1, c - 2, upcomingMove + 1);
printKnightsTour(chess, n, r - 1, c - 2, upcomingMove + 1);
printKnightsTour(chess, n, r - 2, c - 1, upcomingMove + 1);
chess[r][c] = 0;
}
int main() {
int n, r, c;
cin >> n >> r >> c;
vector<vector<int>> chess(n, vector<int> (n, 0));
printKnightsTour(chess, n, r, c, 1);
}