-
Notifications
You must be signed in to change notification settings - Fork 0
/
221.maximal-square.py
83 lines (68 loc) · 1.69 KB
/
221.maximal-square.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Level: Medium
# TAGS: Array, Dynamic Programming, Matrix
from typing import List
class Solution:
# Greedy approach
"""
ref: https://leetcode.com/problems/maximal-square/solutions/600149/python-thinking-process-diagrams-dp-approach/
1 1
1 [1]
Find the min of top, left, top-left if the current is 1
1 1
1 [2]
It means: min(1,1,1) + 1 = 2
Another example
1 1
0 [1]
It will be:
1 1
0 [1]
It means: min(1,1,0) + 1 = 1
Time: O(R*C) | Space: O(1)
"""
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
matrix = [[1 if r == "1" else 0 for r in row] for row in matrix]
R, C = len(matrix), len(matrix[0])
max_side = 0
for i in range(0, R):
if matrix[i][0]:
max_side = 1
for i in range(0, C):
if matrix[0][i]:
max_side = 1
for r in range(1, R):
for c in range(1, C):
if matrix[r][c]:
matrix[r][c] = (
min(matrix[r - 1][c], matrix[r - 1][c - 1], matrix[r][c - 1])
+ 1
)
max_side = max(max_side, matrix[r][c])
return max_side**2
tests = [
(
(
[
["1", "0", "1", "0", "0"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"],
],
),
4,
),
(
([["0", "1"], ["1", "0"]],),
1,
),
(
([["0"]],),
0,
),
(
(["1"],),
1,
),
]