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;
}
}

题解见官方

最新文章

  1. SpringMVC的执行流程(二)
  2. Numpy Study 2----* dot multiply区别
  3. 【Andorid------手势识别】GestureDetector和SimpleOnGestureListener的使用教程(转)——
  4. 利用HTML5的Video进行视频截图并保存到本地
  5. 纸牌project
  6. The Happy Worm 分类: POJ 排序 2015-08-03 18:57 5人阅读 评论(0) 收藏
  7. php flush()刷新不能输出缓冲的原因分析
  8. [转]Mysql导入导出工具Mysqldump和Source命令用法详解
  9. STM32F051关于printf函数在串口打印中的使用
  10. Python系列之模块、和字符串格式化
  11. Leetcode解题-链表(2.2.0)基础类
  12. PHP之十六个魔术方法
  13. 关于visual assist x插件不能用的解决方案
  14. CentOS下安装Docker-CE
  15. Flask web开发之路一
  16. MIR7预制发票扣除已经预制的数量(每月多次预制,未即时过账)
  17. [Flutter] Image.File 加载图像时文件内容变化显示不变解决
  18. Python中新式类和经典类的区别,钻石继承
  19. 25LINQ拾遗及实例
  20. (数据科学学习手札55)利用ggthemr来美化ggplot2图像

热门文章

  1. Ansible基础认识及安装使用详解
  2. ES5中对象的继承
  3. (已解决)MYSQL怎么实现表的id在插入删除的前提下连续递增?
  4. KingbaseES V8R6备份恢复案例之---自定义表空间指定恢复目录数据恢复
  5. 最简spring IOC实现
  6. idea的操作快捷键
  7. vxlan结合iptables-snat实现内网服务器公网访问
  8. 00_k8s_learn
  9. 阿里云仓库构建gcr镜像
  10. Chart控件-常用设置