-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path959 Regions Cut By Slashes.py
154 lines (126 loc) · 2.98 KB
/
959 Regions Cut By Slashes.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#!/usr/bin/python3
"""
In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \,
or blank space. These characters divide the square into contiguous regions.
(Note that backslash characters are escaped, so a \ is represented as "\\".)
Return the number of regions.
Example 1:
Input:
[
" /",
"/ "
]
Output: 2
Explanation: The 2x2 grid is as follows:
Example 2:
Input:
[
" /",
" "
]
Output: 1
Explanation: The 2x2 grid is as follows:
Example 3:
Input:
[
"\\/",
"/\\"
]
Output: 4
Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/,
and "/\\" refers to /\.)
The 2x2 grid is as follows:
Example 4:
Input:
[
"/\\",
"\\/"
]
Output: 5
Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\,
and "\\/" refers to \/.)
The 2x2 grid is as follows:
Example 5:
Input:
[
"//",
"/ "
]
Output: 3
Explanation: The 2x2 grid is as follows:
Note:
1 <= grid.length == grid[0].length <= 30
grid[i][j] is either '/', '\', or ' '.
"""
from typing import List
class DisjointSet:
def __init__(self):
"""
unbalanced DisjointSet
"""
self.pi = {}
def union(self, x, y):
pi_x = self.find(x)
pi_y = self.find(y)
self.pi[pi_y] = pi_x
def find(self, x):
# LHS self.pi[x]
if x not in self.pi:
self.pi[x] = x
if self.pi[x] != x:
self.pi[x] = self.find(self.pi[x])
return self.pi[x]
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
"""
in 1 x 1 cell
3 possibilities
___
| |
|___|
___
| /|
|/__|
___
|\ |
|__\|
4 regions in the
___
|\ /|
|/_\|
"""
m, n = len(grid), len(grid[0])
ds = DisjointSet()
T, R, B, L = range(4) # top, right, bottom, left
for i in range(m):
for j in range(n):
e = grid[i][j]
if e == "/" or e == " ":
ds.union((i, j, B), (i, j, R))
ds.union((i, j, T), (i, j, L))
if e == "\\" or e == " ": # not elif
ds.union((i, j, T), (i, j, R))
ds.union((i, j, B), (i, j, L))
# nbr
if i - 1 >= 0:
ds.union((i, j, T), (i-1, j, B))
if j - 1 >= 0:
ds.union((i, j, L), (i, j-1, R))
# unnessary, half closed half open
# if i + 1 < m:
# ds.union((i, j, B), (i+1, j, T))
# if j + 1 < n:
# ds.union((i, j, R), (i, j+1, L))
return len(set(
ds.find(x)
for x in ds.pi.keys()
))
if __name__ == "__main__":
assert Solution().regionsBySlashes([
" /",
"/ "
]) == 2
assert Solution().regionsBySlashes([
"//",
"/ "
]) == 3