C/C++教程

算法-leetcode-5882. 网格游戏

本文主要是介绍算法-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. 网格游戏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!