Leetcode No. 221 Maximal Square
Problem Description:
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
Analysis:
Algorithm 1:
This problem is very similar to No.85 Maximal Rectangle problem. In fact I tried to solve this problem right after Maximal Rectangle problem, so I naturally came up with a solution based upon that algorithm. The majority of the code remain the same, except when updating the maximum area after each row iteration, instead of calculate1
res = (right[i][j] - left[i][j]) * height[i][j];
We compare height[i][j] and right[i][j] - left[i][j] and take the smaller one as square’s side, then the area is size squared.1
2int r = Math.min(right[i][j] - left[i][j], height[i][j]);
res = r * r;
Algorithm 2:
Still dynamic programming, but this one only uses one matrix.
1 | public class MaximalSquare { |