-
Notifications
You must be signed in to change notification settings - Fork 0
/
m959.py
59 lines (54 loc) · 2.21 KB
/
m959.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
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
def dfs(r: int,
c: int,
qaud: str,
visited: Set[Tuple[int, int, int]],
grid: List[str]) -> None :
if not (0 <= r < len(grid)) or not (0 <= c < len(grid[0])) :
return
if (r, c) in visited :
return
if (r, c, qaud) in visited :
return
if grid[r][c] == ' ' :
visited.add((r, c))
dfs(r - 1, c, 'D', visited, grid)
dfs(r + 1, c, 'U', visited, grid)
dfs(r, c - 1, 'R', visited, grid)
dfs(r, c + 1, 'L', visited, grid)
return
visited.add((r, c, qaud))
if grid[r][c] == '/' :
if qaud == 'U' or qaud == 'L' :
dfs(r, c, 'U', visited, grid)
dfs(r, c, 'L', visited, grid)
dfs(r, c - 1, 'R', visited, grid)
dfs(r - 1, c, 'D', visited, grid)
else :
dfs(r, c, 'D', visited, grid)
dfs(r, c, 'R', visited, grid)
dfs(r, c + 1, 'L', visited, grid)
dfs(r + 1, c, 'U', visited, grid)
else : # \\
if qaud == 'U' or qaud == 'R' :
dfs(r, c, 'U', visited, grid)
dfs(r, c, 'R', visited, grid)
dfs(r, c + 1, 'L', visited, grid)
dfs(r - 1, c, 'D', visited, grid)
else : # L/D
dfs(r, c, 'L', visited, grid)
dfs(r, c, 'D', visited, grid)
dfs(r, c - 1, 'R', visited, grid)
dfs(r + 1, c, 'U', visited, grid)
grid = [x.replace('\\', '.') for x in grid]
visited = set()
counter = 0
for r in range(len(grid)) :
for c in range(len(grid[0])) :
for i in ['R', 'L', 'U', 'D'] :
if (r, c, i) in visited or (r, c) in visited:
continue
counter += 1
dfs(r, c, i, visited, grid)
return counter