forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-knights-tour.cpp
86 lines (79 loc) · 2.94 KB
/
the-knights-tour.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
// Time: O(m * n)
// Space: O(1)
// backtracking, greedy, warnsdorff's rule
class Solution {
public:
vector<vector<int>> tourOfKnight(int m, int n, int r, int c) {
static const vector<pair<int, int>> DIRECTIONS = {{1, 2}, {-1, 2}, {1, -2}, {-1, -2},
{2, 1}, {-2, 1}, {2, -1}, {-2, -1}};
vector<vector<int>> result(m, vector<int>(n, -1));
result[r][c] = 0;
const function<bool(int, int, int)> backtracking = [&](int r, int c, int i) {
const auto& degree = [&](const auto& x) {
int cnt = 0;
const auto& [r, c] = x;
for (const auto& [dr, dc] : DIRECTIONS) {
const int nr = r + dr, nc = c + dc;
if (0 <= nr && nr < m && 0 <= nc && nc < n && result[nr][nc] == -1) {
++cnt;
}
}
return cnt;
};
if (i == m * n) {
return true;
}
vector<pair<int, int>> candidates;
for (const auto& [dr, dc] : DIRECTIONS) {
const int nr = r + dr, nc = c + dc;
if (0 <= nr && nr < m && 0 <= nc && nc < n && result[nr][nc] == -1) {
candidates.emplace_back(nr, nc);
}
}
sort(begin(candidates), end(candidates), [&](const auto& a, const auto& b) {
return degree(a) < degree(b);
});
for (const auto& [nr, nc] : candidates) { // warnsdorff's rule
result[nr][nc] = i;
if (backtracking(nr, nc, i + 1)) {
return true;
}
result[nr][nc] = -1;
}
return false;
};
backtracking(r, c, 1);
return result;
}
};
// Time: O(8^(m * n - 1))
// Space: O(m * n)
// backtracking
class Solution2 {
public:
vector<vector<int>> tourOfKnight(int m, int n, int r, int c) {
static const vector<pair<int, int>> DIRECTIONS = {{1, 2}, {-1, 2}, {1, -2}, {-1, -2},
{2, 1}, {-2, 1}, {2, -1}, {-2, -1}};
vector<vector<int>> result(m, vector<int>(n, -1));
result[r][c] = 0;
const function<bool(int, int, int)> backtracking = [&](int r, int c, int i) {
if (i == m * n) {
return true;
}
for (const auto& [dr, dc] : DIRECTIONS) {
const int nr = r + dr, nc = c + dc;
if (!(0 <= nr && nr < m && 0 <= nc && nc < n && result[nr][nc] == -1)) {
continue;
}
result[nr][nc] = i;
if (backtracking(nr, nc, i + 1)) {
return true;
}
result[nr][nc] = -1;
}
return false;
};
backtracking(r, c, 1);
return result;
}
};