算法-leetcode-5882. 网格游戏
2021/9/26 14:11:03
本文主要是介绍算法-leetcode-5882. 网格游戏,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
dfs+dp
import java.util.ArrayList; import java.util.List; class Solution { int m, n, ans = Integer.MAX_VALUE; public long gridGame(int[][] grid) { m = grid.length; n = grid[0].length; dfs(grid, 0, 0, new ArrayList<>()); return ans; } private void dfs(int[][] grid, int x, int y, List<Integer> list) { if (x == 1 && y == n - 1) { int[][] dp = new int[m][n]; int[][] grid2 = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { grid2[i][j] = grid[i][j]; } } grid2[0][0] = 0; grid2[m - 1][n - 1] = 0; for (int i = 0; i < list.size(); i++) { int xx = list.get(i) / n; int yy = list.get(i) % n; grid2[xx][yy] = 0; } dp[0][0]=grid2[0][0]; dp[1][0]=grid2[1][0]; for (int i = 1; i < n; i++) { dp[0][i]=dp[0][i-1]+grid2[0][i]; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + grid2[i][j]; } } ans = Math.min(ans, dp[m - 1][n - 1]); } else { if (x + 1 < 2) { list.add(x * n + y); dfs(grid, x + 1, y, list); list.remove(list.size() - 1); } if (y + 1 < n) { list.add(x * n + y); dfs(grid, x, y + 1, list); list.remove(list.size() - 1); } } } }
前缀和
class Solution { public long gridGame(int[][] grid) { int n = grid[0].length; long[][] p1 = new long[2][n + 1]; for(int i = 1; i <= n; i++) { p1[0][i] = p1[0][i - 1] + grid[0][i - 1]; p1[1][i] = p1[1][i - 1] + grid[1][i - 1]; } long ans = Long.MAX_VALUE; for(int i = 1; i <= n; i++) { ans = Math.min(ans, Math.max(p1[0][n] - p1[0][i], p1[1][i - 1])); } return ans; } }
这篇关于算法-leetcode-5882. 网格游戏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-29【机器学习(二)】分类和回归任务-决策树(Decision Tree,DT)算法-Sentosa_DSML社区版
- 2024-11-29怎么去掉UniApp中字符串的空格?-icode9专业技术文章分享
- 2024-11-29Warning: Cannot modify header information - headers already sent by 报错信息是什么?-icode9专业技术文章分享
- 2024-11-29Excel中实现拖动排序的简易教程
- 2024-11-29如何在Excel中使用拖动排序功能
- 2024-11-28阿里云 ECS课程:新手入门教程
- 2024-11-27Excel中实现拖动排序的简单教程
- 2024-11-27Rocket消息队列资料:新手入门指南
- 2024-11-27rocket消息队资料详解与入门指南
- 2024-11-27RocketMQ底层原理资料详解入门教程