如果某一位置重复出现(即,玩家的位置和移动顺序都与上一次行动相同),游戏平局。
给你一张图 graph ,并假设两位玩家都都以最佳状态参与游戏:
如果老鼠获胜,则返回 1;
如果猫获胜,则返回 2;
如果平局,则返回 0 。
示例 1:
输入:graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
输出:0
示例 2:
输入:graph = [[1,3],[0],[3],[0,2]]
输出:1
提示:
3 <= graph.length <= 50
1 <= graph[i].length < graph.length
0 <= graph[i][j] < graph.length
graph[i][j] != i
graph[i] 互不相同
猫和老鼠在游戏中总是移动
题解
hard!直接CV!
C++
const int MOUSE_WIN = 1;
const int CAT_WIN = 2;
const int DRAW = 0;
const int MAXN = 51;
class Solution {
public:
int n;
int dp[MAXN][MAXN][MAXN\*2];
vector<vector<int>> graph;
int catMouseGame(vector<vector<int>>& graph) {
this->n = graph.size();
this->graph = graph;
memset(dp, -1, sizeof(dp));
return getResult(1, 2, 0);
}
int getResult(int mouse, int cat, int turns) {
if (turns == n \* 2) {
return DRAW;
}
if (dp[mouse][cat][turns] < 0) {
if (mouse == 0) {
dp[mouse][cat][turns] = MOUSE_WIN;
} else if (cat == mouse) {
dp[mouse][cat][turns] = CAT_WIN;
} else {
getNextResult(mouse, cat, turns);
}
}
return dp[mouse][cat][turns];
}
void getNextResult(int mouse, int cat, int turns) {
int curMove = turns % 2 == 0 ? mouse : cat;
int defaultResult = curMove == mouse ? CAT_WIN : MOUSE_WIN;
int result = defaultResult;
for (int next : graph[curMove]) {
if (curMove == cat && next == 0) {
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 != DRAW) {
break;
}
}
}
dp[mouse][cat][turns] = result;
}
};
java
class Solution {
static final int MOUSE_WIN = 1;
static final int CAT_WIN = 2;
static final int DRAW = 0;
int n;
int[][] graph;
int[][][] dp;
public int catMouseGame(int[][] graph) {
this.n = graph.length;
this.graph = graph;
this.dp = new int[n][n][n \* 2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Arrays.fill(dp[i][j], -1);
}
}
return getResult(1, 2, 0);
}
public int getResult(int mouse, int cat, int turns) {
if (turns == n \* 2) {
return DRAW;
}
if (dp[mouse][cat][turns] < 0) {
if (mouse == 0) {
dp[mouse][cat][turns] = MOUSE_WIN;
} else if (cat == mouse) {
dp[mouse][cat][turns] = CAT_WIN;
} else {