题目
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:
1 | Input: |
思路
DP.
两种DP方法(实际是一种).
dp(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix.
dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1.
Time complexity : O(mn)
Space complexity : O(mn)In the previous approach for calculating dp of $i^{th}$row we are using only the previous element and the $(i-1)^{th}$row. Therefore, we don’t need 2D dp matrix as 1D dp array will be sufficient for this.
dp[j]=min(dp[j-1],dp[j],prev), prev = old dp[j-1].
Time complexity : O(mn)
Space complexity : O(n)
代码
1 | # # 2d DP: dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1. |