const int MOUSE_WIN = 1;
const int CAT_WIN = 2;
const int DRAW = 0;
const int MAXN = 51;
class Solution {
int n;
int dp[MAXN * 2][MAXN][MAXN];
vector<vector<int>> g;
public:
int catMouseGame(vector<vector<int>>& graph) {
n = graph.size();
g = graph;
memset(dp, -1, sizeof(dp));
return dfs(0, 1, 2);
}
int dfs(int k, int a, int b) {
int ans = dp[k][a][b];
if (a == 0) ans = 1;
else if (a == b) ans = 2;
else if (k >= 2 * n) ans = 0;
else if (ans == -1) {
bool win = false, draw = false;
if (k % 2 == 0) { // mouse
for (int ne : g[a]) {
int t = dfs(k + 1, ne, b);
if (t == 1)
{
win = true;
break;
}
else if (t == 0)
{
draw = true;
}
}
if (win) ans = 1;
else if (draw) ans = 0;
else ans = 2;
} else { // cat
for (int ne : g[b]) {
if (ne == 0) continue;
int t = dfs(k + 1, a, ne);
if (t == 2) {
win = true;
break;
}
else if (t == 0) {
draw = true;
}
}
if (win) ans = 2;
else if (draw) ans = 0;
else ans = 1;
}
}
dp[k][a][b] = ans;
return ans;
}
};
直接cv的三叶姐代码,目前的水平还驾驭不住这种难度的题
假期有时间看看动态规划~