Hard
Number of Valid Move Combinations On Chessboard — C++
Full explanation · Time O(1) · Space O(1)
// 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;
}
};