题意:给定一个无向图,猫和老鼠分别在各自的起点轮流启动,问猫能否抓到老鼠或老鼠能否逃回洞内;
传送门
两位玩家分别扮演猫和老鼠,在一张 无向 图上进行游戏,两人轮流行动。
老鼠从节点 1 开始,第一个出发;猫从节点 2 开始,第二个出发。在节点 0 处有一个洞。
在每个玩家的行动中,他们 必须 沿着图中与所在当前位置连通的一条边移动。例如,如果老鼠在节点 1 ,那么它必须移动到 graph[1] 中的任一节点。
此外,猫无法移动到洞中(节点 0)。
然后,游戏在出现以下三种情形之一时结束:
- 如果猫和老鼠出现在同一个节点,猫获胜。
- 如果老鼠到达洞中,老鼠获胜。
- 如果某一位置重复出现(即,玩家的位置和移动顺序都与上一次行动相同),游戏平局。
给你一张图 graph ,并假设两位玩家都都以最佳状态参与游戏:
- 如果老鼠获胜,则返回 1;
- 如果猫获胜,则返回 2;
- 如果平局,则返回 0 。
输入:graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
输出:0
当n >= 2*n,猫和老鼠把整个图都走了一遍,此时如还没有出现必胜或必败,则为和,因为重复下去也不会有更好的结果。
int catMouseGame(vector<vector<int>>& graph) {
int n = graph.size();
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(n+1, vector<int>(2*n+2, -1)));
function<int(int,int,int)> getResult = [&](int mouse, int cat, int turns) {
if (turns == n*2) return 0;
if (dp[mouse][cat][turns] < 0) {
if (!mouse)
dp[mouse][cat][turns] = 1;
else if (cat == mouse)
dp[mouse][cat][turns] = 2;
else {
int curMove = turns % 2 == 0 ? mouse : cat;
int defaultResult = curMove == mouse ? 2 : 1;
int result = defaultResult;
for (int &next : graph[curMove]) {
if (curMove == cat && !next)
continue;
int nextMouse = curMove == mouse ? next : mouse;
int nextCat = curMove == cat ? next : cat;
int nextResult = getResult(nextMouse, nextCat, turns+1);
if (nextResult != defaultResult) {
result = nextResult;
if (result)
break;
}
}
dp[mouse][cat][turns] = result;
}
}
return dp[mouse][cat][turns];
};
return getResult(1, 2, 0);
}