MediumPythonJavaScriptTypeScript
DP — Maximal Square
AlgorithmsDynamic ProgrammingMatrix
solve(matrix) — a matrix of 0 and 1. Return the area of the largest square
that contains only 1s (0 if there is none).
Let side[r][c] be the side of the largest all-ones square whose **bottom-right
corner** is (r, c). If the cell is 1, thenside = 1 + min(side[r-1][c], side[r][c-1], side[r-1][c-1]); otherwise it is 0.
Examples
solve([[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]) → 4
solve([[0,1],[1,0]]) → 1
solve([[0]]) → 0
solve([[1,1],[1,1]]) → 4Sample tests
Test #1Classic example
Input: [[[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]]
Output: 4
Test #2Only single cells
Input: [[[0,1],[1,0]]]
Output: 1
Test #3No ones
Input: [[[0]]]
Output: 0