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
|
#include <vector>
#include <queue>
#include <tuple>
#include <unordered_map>
using namespace std;
class Solution {
public:
int maxMoves(int kx, int ky, vector<vector<int>>& positions) {
int n = positions.size();
vector<pair<int, int>> pawns;
for (auto& p : positions) pawns.emplace_back(p[0], p[1]);
vector<vector<int>> dist(n+1, vector<int>(n, 0));
auto bfs = [&](int sx, int sy) -> vector<int> {
vector<vector<int>> d(50, vector<int>(50, -1));
queue<pair<int, int>> q;
q.emplace(sx, sy);
d[sx][sy] = 0;
vector<int> res(n);
int dx[8] = {-2,-2,-1,-1,1,1,2,2}, dy[8] = {-1,1,-2,2,-2,2,-1,1};
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int k = 0; k < 8; ++k) {
int nx = x + dx[k], ny = y + dy[k];
if (nx >= 0 && nx < 50 && ny >= 0 && ny < 50 && d[nx][ny] == -1) {
d[nx][ny] = d[x][y] + 1;
q.emplace(nx, ny);
}
}
}
for (int i = 0; i < n; ++i) res[i] = d[pawns[i].first][pawns[i].second];
return res;
};
dist[0] = bfs(kx, ky);
for (int i = 0; i < n; ++i) dist[i+1] = bfs(pawns[i].first, pawns[i].second);
unordered_map<long long, int> memo;
function<int(int, int, int, bool)> dfs = [&](int pos, int mask, int turn, bool alice) -> int {
long long key = ((long long)pos << 16) | (mask << 1) | alice;
if (memo.count(key)) return memo[key];
int best = alice ? -1e9 : 1e9;
bool any = false;
for (int i = 0; i < n; ++i) {
if (!(mask & (1 << i))) continue;
int d = dist[pos][i];
if (d < 0) continue;
any = true;
int next = dfs(i+1, mask ^ (1 << i), turn+1, !alice) + d;
if (alice) best = max(best, next);
else best = min(best, next);
}
if (!any) return 0;
return memo[key] = best;
};
return dfs(0, (1<<n)-1, 0, true);
}
};
|