File tree 1 file changed +33
-1
lines changed
2024/python/src/grice_py_aoc_2024/day12
1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change 7
7
FILE = DIR .parents [3 ] / "inputs" / f"{ DIR .stem } .txt"
8
8
9
9
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
+
10
35
def part1 (grid : list [str ]) -> int :
11
36
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
13
45
return total
14
46
15
47
You can’t perform that action at this time.
0 commit comments