-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpart_one.py
78 lines (55 loc) · 1.79 KB
/
part_one.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
from typing import override
from infrastructure.solutions.base import Solution
class Year2024Day12Part1Solution(Solution):
MOVES = (
(0, 1),
(0, -1),
(1, 0),
(-1, 0),
)
@classmethod
@override
def parse_input(cls, text_input: str) -> dict[str, list[list[str]]]:
garden = []
for line in text_input.split('\n'):
garden.append(list(line))
return {'garden': garden}
@classmethod
@override
def solve(cls, garden: list[list[str]]) -> int:
"""
Time: O(n*m)
Space: O(n*m)
Where n - number of rows in garden,
m - number of columns in garden
"""
n = len(garden)
m = len(garden[0])
visited = set()
def dfs(i: int, j: int, plant: str) -> tuple[int, int]:
# Zero area, one perimeter side
if not (0 <= i < n and 0 <= j < m):
return 0, 1
# Zero area, one perimeter side
if garden[i][j] != plant:
return 0, 1
# Already processed
if (i, j) in visited:
return 0, 0
visited.add((i, j))
area = 1
perimeter = 0
for di, dj in cls.MOVES:
next_i, next_j = i + di, j + dj
next_area, next_perimeter = dfs(next_i, next_j, plant)
area += next_area
perimeter += next_perimeter
return area, perimeter
total_price = 0
for i, row in enumerate(garden):
for j, plant in enumerate(row):
area, perimeter = dfs(i, j, plant)
total_price += area * perimeter
return total_price
if __name__ == '__main__':
print(Year2024Day12Part1Solution.main())