|
|
@@ -0,0 +1,59 @@
|
|
|
+package leetcode.p1594;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @ProjectName: LeetCode
|
|
|
+ * @FileName: Solution
|
|
|
+ * @Author: 杨逸
|
|
|
+ * @Data:2026/3/23 14:13
|
|
|
+ * @Description: https://leetcode.cn/problems/maximum-non-negative-product-in-a-matrix/
|
|
|
+ * 1594. 矩阵的最大非负积
|
|
|
+ */
|
|
|
+public class Solution {
|
|
|
+ private final static int MOD = (int)1e9 + 7;
|
|
|
+ private long[][][] dp;
|
|
|
+ public int maxProductPath(int[][] grid) {
|
|
|
+ /**
|
|
|
+ * 因需要考虑负负得正,所有需要记录最大值和最小值
|
|
|
+ */
|
|
|
+ dp = new long[grid.length][grid[0].length][2];
|
|
|
+ for (long[][] longs : dp) {
|
|
|
+ for (long[] aLong : longs) {
|
|
|
+ aLong[0] = Long.MIN_VALUE;
|
|
|
+ aLong[1] = Long.MIN_VALUE;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ long[] ans = dfs(grid.length - 1, grid[0].length - 1, grid);
|
|
|
+ long res = ans[1] < 0 ? -1 : ans[1] % MOD;
|
|
|
+ return (int)res;
|
|
|
+ }
|
|
|
+
|
|
|
+ private long[] dfs(int x, int y, int[][] grid) {
|
|
|
+ if (x ==0 && y == 0) {
|
|
|
+ int v = grid[x][y];
|
|
|
+ return new long[]{v, v};
|
|
|
+ }
|
|
|
+
|
|
|
+ long current[] = dp[x][y];
|
|
|
+ if (current[1] != Long.MIN_VALUE) {
|
|
|
+ return current;
|
|
|
+ }
|
|
|
+ long min = Long.MAX_VALUE,max = Long.MIN_VALUE;
|
|
|
+ if (x>0) {
|
|
|
+ long[] dfs = dfs(x - 1, y, grid);
|
|
|
+ min = Math.min(min,dfs[0] * grid[x][y]);
|
|
|
+ min = Math.min(min,dfs[1] * grid[x][y]);
|
|
|
+ max = Math.max(max,dfs[0] * grid[x][y]);
|
|
|
+ max = Math.max(max,dfs[1] * grid[x][y]);
|
|
|
+ }
|
|
|
+ if (y>0) {
|
|
|
+ long[] dfs = dfs(x, y - 1, grid);
|
|
|
+ min = Math.min(min,dfs[0] * grid[x][y]);
|
|
|
+ min = Math.min(min,dfs[1] * grid[x][y]);
|
|
|
+ max = Math.max(max,dfs[0] * grid[x][y]);
|
|
|
+ max = Math.max(max,dfs[1] * grid[x][y]);
|
|
|
+ }
|
|
|
+ current[0] = min;
|
|
|
+ current[1] = max;
|
|
|
+ return current;
|
|
|
+ }
|
|
|
+}
|