-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
30 lines (22 loc) · 866 Bytes
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from typing import List
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
rows, cols = len(matrix), len(matrix[0])
cache = {}
def helper(r, c):
if r >= rows or c >= cols:
return 0
if (r, c) not in cache:
down = helper(r + 1, c)
right = helper(r, c + 1)
diag = helper(r + 1, c + 1)
cache[(r, c)] = 0
if matrix[r][c] == "1":
cache[(r, c)] = 1 + min(down, right, diag)
return cache[(r, c)]
helper(0, 0)
return max(cache.values()) ** 2
if __name__ == '__main__':
matrix = [["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"]]
print(Solution().maximalSquare(matrix))