Maximal Square
medium
dynamic-programming
matrix
You are given an m x n binary matrix matrix containing only the integer values 0 and 1 (not characters). Return the area of the largest square that contains only 1s.
Input / output
- Input:
matrix: int[][] - Output:
int(the area of the largest all-1square)
Examples
matrix = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]returns4because the largest all-1square has side length2.matrix = [[0,1],[1,0]]returns1because every all-1square is only a single cell.matrix = [[1]]returns1.
Constraints
1 <= matrix.length, matrix[0].length <= 300matrix[i][j]is either0or1
Follow-up
Can you reduce the dynamic-programming space from O(m*n) to O(n) by keeping only the previous row while preserving the same transition?
Examples
Example 1
Input: matrix = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]
Output: 4
Example 2
Input: matrix = [[0,1],[1,0]]
Output: 1