zoukankan      html  css  js  c++  java
  • 01二维矩阵中最大全为1的正方形maxSquare——经典DP问题(二维)

    在一个二维01矩阵中找到全为1的最大正方形

    1 0 1 0 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0


    以矩阵中每一个点作为正方形右下角点来处理,而以该点为右下角点的最大边长最多比以它的左方、上方和左上方为右下角的正方形边长多1,所以这时只能取另外三个正方形中最小的正方形边长+1。用d[i][j]表示以i,j坐标为右下角的正方形最大边。则有状态转移方程:dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1,具体代码如下:

     public static int maxSquare(int[][] matrix) {
            if (matrix.length==0||matrix[0].length==0) {
                return 0;
            }
            int M = matrix.length, N = matrix[0].length, res = 0;
            int[][] dp = new int[M][N];
            for (int i=0; i<M; i++) {
                if (matrix[i][0] == 1) {
                    dp[i][0] = 1;
                    res = 1;
                }
            }

            for (int j=0; j<N; j++) {
                if (matrix[0][j] == 1) {
                    dp[0][j] = 1;
                    res = 1;
                }
            }

            for (int i=1; i<M; i++) {
                for (int j=1; j<N; j++) {
                    if (matrix[i][j] == 1) {
                        dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
                    }
                    res = max(res, dp[i][j]);
                }
            }
            return res;
        }

    采用动态规划方法正向依次利用之前存储的状态计算出下一个状态值,从而避免了重复计算,大大提升了时间复杂度。

  • 相关阅读:
    Codeforces Beta Round #92 (Div. 2 Only) B. Permutations 模拟
    POJ 3281 Dining 最大流 Dinic算法
    POJ 2441 Arrange the BUlls 状压DP
    URAL 1152 Faise Mirrors 状压DP 简单题
    URAL 1039 Anniversary Party 树形DP 水题
    URAL 1018 Binary Apple Tree 树形DP 好题 经典
    pytorch中的forward前向传播机制
    .data()与.detach()的区别
    Argparse模块
    pytorch代码调试工具
  • 原文地址:https://www.cnblogs.com/bonelee/p/10154306.html
Copyright © 2011-2022 走看看