-
Notifications
You must be signed in to change notification settings - Fork 0
/
302.py
85 lines (70 loc) · 2.1 KB
/
302.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
"""
Problem:
You are given a 2-d matrix where each cell consists of either /, \, or an empty space.
Write an algorithm that determines into how many regions the slashes divide the space.
For example, suppose the input for a three-by-six grid is the following:
\ /
\ /
\/
Considering the edges of the matrix as boundaries, this divides the grid into three
triangles, so you should return 3.
"""
from typing import Set, Tuple
def explore_region(
position: Tuple[int, int], empty_spaces: Set, nrows: int, ncols: int
) -> None:
# dfs helper to remove all adjoining empty spaces for each region
if position not in empty_spaces:
return
# travelling to the adjoining spaces
empty_spaces.remove(position)
x, y = position
if x > 0:
explore_region((x - 1, y), empty_spaces, nrows, ncols)
if x < nrows - 1:
explore_region((x + 1, y), empty_spaces, nrows, ncols)
if y > 0:
explore_region((x, y - 1), empty_spaces, nrows, ncols)
if y < ncols - 1:
explore_region((x, y + 1), empty_spaces, nrows, ncols)
def get_region_count(matrix: str) -> int:
nrows, ncols = len(matrix), len(matrix[0])
empty_spaces = set()
for row in range(nrows):
for col in range(ncols):
if matrix[row][col] == " ":
empty_spaces.add((row, col))
# traversing through the empty spaces
regions = 0
while empty_spaces:
# random position selection
for pos in empty_spaces:
position = pos
break
explore_region(position, empty_spaces, nrows, ncols)
regions += 1
return regions
if __name__ == "__main__":
matrix = [
list(r"\ /"),
list(r" \ / "),
list(r" \/ ")
]
print(get_region_count(matrix))
matrix = [
list(r" /"),
list(r" \ / "),
list(r" \/ ")
]
print(get_region_count(matrix))
matrix = [
list(r" /"),
list(r" \ / "),
list(r" \ ")
]
print(get_region_count(matrix))
"""
SPECS:
TIME COMPLEXITY: O(row x column)
SPACE COMPLEXITY: O(row x column)
"""