博弈论[leetocde913]
2024-10-21 10:12:55
class Solution {
static final int MOUSE_WIN = 1;
static final int CAT_WIN = 2;
static final int DRAW = 0; int n;
int[][][] dp; // dp[mouse][cat][turns]:表示在经历turns轮次,老鼠在mouse位置,猫在cat位置时游戏的状态
int[][] graph; 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);
} private int getResult(int mouse, int cat, int turns) {
if (turns == 2*n) {
return DRAW;
} // 未分出比赛状态
if (dp[mouse][cat][turns] == -1) {
if (mouse == 0) {
dp[mouse][cat][turns] = MOUSE_WIN;
} else if (mouse == cat) {
dp[mouse][cat][turns] = CAT_WIN;
} else {
getNextResult(mouse, cat, turns);
}
} return dp[mouse][cat][turns];
} private void getNextResult(int mouse, int cat, int turns) {
// turns 为偶数时,老鼠先走
int curMove = turns % 2 == 0? mouse: cat;
int notHopeResult = curMove == mouse? CAT_WIN: MOUSE_WIN; int result = notHopeResult;
int[] nextNodes = graph[curMove];
for (int next: nextNodes) {
if (curMove == cat && next == 0) continue; // 猫无法移动到0
int nextCat = curMove == cat? next: cat;
int nextMouse = curMove == mouse? next: mouse;
int nextResult = getResult(nextMouse, nextCat, turns + 1); if (nextResult != notHopeResult) { // 对于老鼠来说:他不希望nextResult为猫赢
result = nextResult;
if (result != DRAW) break; // 已经分出胜负,则无需再比赛;若为平局则一直试探下一个next
}
} dp[mouse][cat][turns] = result;
}
}
题解见官方
最新文章
- SpringMVC的执行流程(二)
- Numpy Study 2----* dot multiply区别
- 【Andorid------手势识别】GestureDetector和SimpleOnGestureListener的使用教程(转)——
- 利用HTML5的Video进行视频截图并保存到本地
- 纸牌project
- The Happy Worm 分类: POJ 排序 2015-08-03 18:57 5人阅读 评论(0) 收藏
- php flush()刷新不能输出缓冲的原因分析
- [转]Mysql导入导出工具Mysqldump和Source命令用法详解
- STM32F051关于printf函数在串口打印中的使用
- Python系列之模块、和字符串格式化
- Leetcode解题-链表(2.2.0)基础类
- PHP之十六个魔术方法
- 关于visual assist x插件不能用的解决方案
- CentOS下安装Docker-CE
- Flask web开发之路一
- MIR7预制发票扣除已经预制的数量(每月多次预制,未即时过账)
- [Flutter] Image.File 加载图像时文件内容变化显示不变解决
- Python中新式类和经典类的区别,钻石继承
- 25LINQ拾遗及实例
- (数据科学学习手札55)利用ggthemr来美化ggplot2图像