Skip to content

Commit fec56a8

Browse files
committed
feat: day 12 partial (all parts incomplete)
1 parent 9ef8796 commit fec56a8

File tree

1 file changed

+33
-1
lines changed
  • 2024/python/src/grice_py_aoc_2024/day12

1 file changed

+33
-1
lines changed

2024/python/src/grice_py_aoc_2024/day12/main.py

+33-1
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,41 @@
77
FILE = DIR.parents[3] / "inputs" / f"{DIR.stem}.txt"
88

99

10+
def _calc_fence_perimeter(grid: list[str], x: int, y: int, char: str) -> int:
11+
len_x, len_y = len(grid), len(grid[0])
12+
fences = 0
13+
for dx, dy in [
14+
(1, 0),
15+
(0, -1),
16+
(0, 1),
17+
(-1, 0),
18+
]:
19+
newx, newy = x + dx, y + dy
20+
if not 0 <= newx < len_x or not 0 <= newy < len_y:
21+
# Position is outside the grid: this side naturally has a fence.
22+
fences += 1
23+
elif char != grid[newx][newy]:
24+
# The adjacent region is not the same as our current one,
25+
# so a dividing fence is needed.
26+
fences += 1
27+
# Natural 'else' is an adjacent region with the same type of flower,
28+
# so no fence is needed there.
29+
return fences
30+
31+
32+
MAX_FENCE = 4
33+
34+
1035
def part1(grid: list[str]) -> int:
1136
total = 0
12-
# TODO part 1
37+
for x, line in enumerate(grid):
38+
for y, char in enumerate(line):
39+
fences_here = _calc_fence_perimeter(grid=grid, x=x, y=y, char=char)
40+
if fences_here == MAX_FENCE:
41+
# This is a self-contained region: no further calculation needed.
42+
# Area is 1, with 4 fences
43+
total += fences_here
44+
continue
1345
return total
1446

1547

0 commit comments

Comments
 (0)