-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.cpp
74 lines (56 loc) · 1.58 KB
/
main.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
//
// main.cpp
// Knight’s tour
//
// Created by Ngoc Nguyen on 11/5/19.
// Copyright © 2019 Ngoc Nguyen. All rights reserved.
//
// https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
#include <iostream>
#define N 5
using namespace std;
int matrix[N][N];
bool isSafe(int x, int y) {
return x >= 0 && y >= 0 && x <= N - 1 && y <= N-1;
}
int dfs(int x, int y, int cnt) {
int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
for (int i=0; i < 8; i++) {
int nextX = x + xMove[i];
int nextY = y + yMove[i];
if (cnt == N*N) {
return 1;
}
if (isSafe(nextX, nextY)) {
if (matrix[nextX][nextY] == -1) {
matrix[nextX][nextY] = cnt + 1;
if (dfs(nextX, nextY, cnt+1) == 1) {
return 1;
} else {
matrix[nextX][nextY] = -1; // Solution 1.
}
}
}
}
// matrix[x][y] = -1; // Solution 2.
return 0;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "The Knight’s tour problem\n";
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = -1;
}
}
matrix[0][0] = 1;
dfs(0, 0, 1);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << matrix[i][j] << "-";
}
cout << "\n" << endl;
}
return 0;
}