-
Notifications
You must be signed in to change notification settings - Fork 17
/
regions-cut-by-slashes.py
96 lines (74 loc) · 3.35 KB
/
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
from enum import Enum
from typing import List, Iterator, Tuple
class GridCharacter(Enum):
SPACE = 0
SLASH = 1
BACKSLASH = 2
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
def neighbours(
visited: List[List[bool]], row: int, col: int, rows: int, cols: int
) -> Iterator[Tuple[int, int]]:
for neigh_row, neigh_col in (
(row + 1, col),
(row - 1, col),
(row, col + 1),
(row, col - 1),
):
if (
0 <= neigh_row < rows
and 0 <= neigh_col < cols
and not visited[neigh_row][neigh_col]
):
yield neigh_row, neigh_col
def paint(
visited: List[List[bool]], row: int, col: int, rows: int, cols: int
) -> None:
visited[row][col] = True
for neigh_row, neigh_col in neighbours(visited, row, col, rows, cols):
paint(visited, neigh_row, neigh_col, rows, cols)
def grid_normalize(grid: List[str]) -> List[List[GridCharacter]]:
grid_normalized: List[List[GridCharacter]] = [[] for _ in grid]
for row in range(len(grid)):
pos = 0
while pos < len(grid[row]):
if grid[row][pos] == " ":
grid_normalized[row].append(GridCharacter.SPACE)
pos += 1
elif grid[row][pos] == "/":
grid_normalized[row].append(GridCharacter.SLASH)
pos += 1
else:
grid_normalized[row].append(GridCharacter.BACKSLASH)
pos += 1
return grid_normalized
def grid_to_picture(grid: List[str]) -> List[List[bool]]:
grid_normalized = grid_normalize(grid)
grid_rows, grid_cols = (
len(grid_normalized),
len(grid_normalized[0]) if grid_normalized else 0,
)
picture_rows, picture_cols = grid_rows * 3 + 1, grid_cols * 3 + 1
picture = [[False] * picture_cols for _ in range(picture_rows)]
for grid_row in range(grid_rows):
for grid_col in range(grid_cols):
if grid_normalized[grid_row][grid_col] == GridCharacter.BACKSLASH:
top_left_row, top_left_col = grid_row * 3, grid_col * 3
for offset in range(4):
picture[top_left_row + offset][top_left_col + offset] = True
elif grid_normalized[grid_row][grid_col] == GridCharacter.SLASH:
top_right_row, top_right_col = grid_row * 3, grid_col * 3 + 3
for offset in range(4):
picture[top_right_row + offset][
top_right_col - offset
] = True
return picture
picture: List[List[bool]] = grid_to_picture(grid)
rows, cols = len(picture), len(picture[0]) if picture else 0
regions = 0
for row in range(rows):
for col in range(cols):
if not picture[row][col]:
paint(picture, row, col, rows, cols)
regions += 1
return regions