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
To apply DP, we define the state as the maximal size (square = size * size) of the square that can be formed till point (i, j), denoted as dp[i][j].
For the topmost row (i = 0) and the leftmost column (j = 0), we have dp[i][j] = matrix[i][j] - ‘0’, meaning that it can at most form a square of size 1 when the matrix has a ‘1’ in that cell.
When i > 0 and j > 0, if matrix[i][j] = ‘0’, then dp[i][j] = 0 since no square will be able to contain the ‘0’ at that cell. If matrix[i][j] = ‘1’, we will have dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1, which means that the square will be limited by its left, upper and upper-left neighbors.
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1: 约束该点最大方形面积的三个因素: 左边延申的距离, 上面延申的距离, 左上延申的距离(对角线)
1 | class Solution { |
In the above code, it uses O(mn) space. Actually each time when we update dp[i][j], we only need dp[i-1][j-1], dp[i-1][j] (the previous row) and dp[i][j-1] (the current row). So we may just keep two rows.
1 | class Solution { |
Furthermore, we may only use just one vector
1 | class Solution { |