zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Contains Duplicate IIIMaximal Square

    题目:

    Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

    For example, given the following matrix:

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

    Return 4.

    思路:动态规划,逐步保存节点处能达到的最优值,为了方便存储以该点为右下角的矩形内,满足条件的 最大的正方形的边长。

    当循环到 matrix[i][j]时候,如果该处的char值为1,则状态转移方程为 dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;

    代码:

    public class Solution {
        public int maximalSquare(char[][] matrix) {
            int m = matrix.length;
            if(m == 0) return 0;
            int n = matrix[0].length;
            
            int[][] dp = new int[m][n];
            
            int area = 0;
            for(int i = 0 ; i < m ; i++){
                for(int j = 0 ; j < n ; j ++){
                    dp[i][j] = matrix[i][j] - '0';
                    if(i-1 >= 0 && j-1 >=0 && dp[i][j] > 0){
                        dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
                    }
                    if(dp[i][j] > area)
                        area = dp[i][j];
                }
            }
            
            return area*area;
        }
    }
  • 相关阅读:
    逆序对的相关问题:bzoj1831,bzoj2431
    bzoj3211,bzoj3038
    hdu 1179最大匹配
    hdu 3038带权并查集
    poj 1733离散化(map)+并查集
    codeforces 369B
    poj 1456
    POJ 1988相对偏移
    poj 1986tarjan模板题
    poj 1330lca模板题离线算法
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4552099.html
Copyright © 2011-2022 走看看