forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-valid-move-combinations-on-chessboard.cpp
51 lines (48 loc) · 2.14 KB
/
number-of-valid-move-combinations-on-chessboard.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
// Time: O(n^p) = O(1), n is the max number of possible moves for each piece, and n is at most 29
// , p is the number of pieces, and p is at most 4
// Space: O(1)
class Solution {
public:
int countCombinations(vector<string>& pieces, vector<vector<int>>& positions) {
vector<vector<int>> lookup(8, vector<int>(8));
return backtracking(pieces, positions, 0, &lookup);
}
private:
int backtracking(const vector<string>& pieces, const vector<vector<int>>& positions, int i, vector<vector<int>> *lookup) {
static const unordered_map<string, vector<pair<int, int>>> directions = {
{"rook", {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}},
{"bishop", {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}},
{"queen", {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}}
};
static const int all_mask = (1 << 7) - 1; // at most 7 seconds in 8x8 board
if (i == size(pieces)) {
return 1;
}
int result = 0;
int r = positions[i][0] - 1, c = positions[i][1] - 1;
int mask = all_mask;
if (!((*lookup)[r][c] & mask)) {
(*lookup)[r][c] += mask; // stopped at (r, c)
result += backtracking(pieces, positions, i + 1, lookup);
(*lookup)[r][c] -= mask;
}
for (const auto& [dr, dc] : directions.at(pieces[i])) {
int bit = 1, nr = r + dr, nc = c + dc;
int mask = all_mask; // (mask&bit == 1): (log2(bit)+1)th second is occupied
for (; 0 <= nr && nr < 8 && 0 <= nc && nc < 8 && !((*lookup)[nr][nc] & bit); bit <<= 1, nr += dr, nc += dc) {
(*lookup)[nr][nc] += bit;
mask -= bit;
if (!((*lookup)[nr][nc] & mask)) { // stopped at (nr, nc)
(*lookup)[nr][nc] += mask;
result += backtracking(pieces, positions, i + 1, lookup);
(*lookup)[nr][nc] -= mask;
}
}
while (bit >> 1) {
bit >>= 1, nr -= dr, nc -= dc;
(*lookup)[nr][nc] -= bit;
}
}
return result;
}
};