221 Maximal Square
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
For example, given the following matrix:
Return 4.
The Idea: Harness the power of DP. Store the matrix as a submatrix of an n+1 larger matrix. Then, for each element in the submatrix, find the min(left, right, diag) + 1
. The above example will in effect become:
The intuition is that we want to find a way that tells us what size our square matrix is by looking it's surrounding neighbors. A 4 by 4 square for example, can become decomposed as follows:
Notice how every number is true for every subsquare in the matrix. Once we know what matrix we want to generate, we can reverse engineer a formula (min(left, right, diag) + 1
) that makes this true.
Complexity: O(2n) time (extra time converting char matrix to int matrix) and O(1) space
Last updated