zoukankan      html  css  js  c++  java
  • [LeetCode 221] Maximal 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.

     

    Solution 1.  For each entry of 1, use it as a possible bottom right point of a square of all 1s, then find the largest square of all 1s for this entry. The runtime is O(n^4): O(n^2) possible entries and O(n^2) time for each check.

    The problem of this solution is that for each entry of 1, we start from scratch to check. We basically throw all the previous check results for previous entries of 1. Take the following example, when checking the entry of red color, we've already checked entries of yellow, green and purple that they all form a length 3 square. However solution 1 discard these infos and checked all the entries in the 4 by 4 grid to determine it actually forms a length 4 square.  Instead, its neighboring results(left, top and top left) can be used to get a O(1) check as shown in solution 2.

    1 1 1 1

    1 1 1 1

    1 1 1 1

    1 1 1 1

     

    Solution 2. Dynamic Programming, O(n^2) runtime, O(n^2) space 

    State: dp[i][j] : the max length of the square of all 1s whose bottom right point is matrix[i][j].

    State Transition: dp[i][j] == 0, if matrix[i][j] == 0;  dp[i][j] = 1 + min{dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]}, if matrix[i][j] == 1.

    Initialization: dp[i][0] = matrix[i][0]; dp[0][j] = matrix[0][j]. 

    class Solution {
        public int maximalSquare(char[][] matrix) {
            if(matrix.length == 0) {
                return 0;
            }
            int n = matrix.length, m = matrix[0].length;
            int[][] dp = new int[n][m]; //dp[i][j]: the max side length of square whose bottom right corner is (i, j).
            int ans = 0;
            for(int i = 0; i < n; i++) {
                for(int j = 0; j < m; j++) {
                    if(matrix[i][j] == '1') {
                        dp[i][j] = 1;
                        if(i > 0 && j > 0) {
                            dp[i][j] = Math.max(dp[i][j], Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1);
                        }
                        ans = Math.max(ans, dp[i][j] * dp[i][j]);
                    }
                }
            }
            return ans;
        }
    }

    Related Problems 

    Maximal Square II

    Maximum Subsquare surrounded by 'X'

  • 相关阅读:
    Win10下PB停在欢迎窗口界面
    iReport 中使用 Chart 图
    iReport 下载地址
    使用jasperreports-5.6.0.jar导致的问题
    iReport 开发和运行所用版本不一致导致设置字体大小不起作用
    AWS SAA summary--Exam
    构建zabbix监控实验-基础篇
    常用数据结构代码示例
    嵌入式相关知识点整理
    ADB 环境变量配置
  • 原文地址:https://www.cnblogs.com/lz87/p/7393778.html
Copyright © 2011-2022 走看看