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].
Function: 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].
1 public class Solution { 2 public int maxSquare(int[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ 4 return 0; 5 } 6 int n = matrix.length; int m = matrix[0].length; 7 int[][] dp = new int[n][m]; 8 for(int i = 0; i < n; i++){ 9 dp[i][0] = matrix[i][0]; 10 } 11 for(int j = 0; j < m; j++){ 12 dp[0][j] = matrix[0][j]; 13 } 14 for(int i = 1; i < n; i++){ 15 for(int j = 1; j < m; j++){ 16 if(matrix[i][j] == 0){ 17 dp[i][j] = 0; 18 } 19 else{ 20 dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1; 21 } 22 } 23 } 24 int max = 0; 25 for(int i = 0; i < n; i++){ 26 for(int j = 0; j < m; j++){ 27 max = Math.max(max, dp[i][j]); 28 } 29 } 30 return max * max; 31 } 32 }
Related Problems
本文介绍了如何在二维二进制矩阵中寻找包含全1的最大正方形,并返回其面积。提供了两种解决方案:一种是效率较低的时间复杂度为O(n^4)的方法;另一种是使用动态规划的高效解法,时间复杂度为O(n^2)。动态规划方法通过记录每个位置为正方形右下角时最大正方形的边长,实现了快速查找。
236

被折叠的 条评论
为什么被折叠?



