Day 12: Garden Groups

2024-12-12

Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search.

You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots.

Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example:

1
2
3
4
AAAA BBCD BBCC EEEC

This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region.

In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter.

The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1.

Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4.

Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
+-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+

Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example:

1
2
3
4
5
OOOOO OXOXO OOOOO OXOXO OOOOO

The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot.

The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36.

Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map.

In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140.

In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4).

Here's a larger example:

1
2
3
4
5
6
7
8
9
10
RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE

It contains:

  • A region of R plants with price 12 * 18 = 216.
  • A region of I plants with price 4 * 8 = 32.
  • A region of C plants with price 14 * 28 = 392.
  • A region of F plants with price 10 * 18 = 180.
  • A region of V plants with price 13 * 20 = 260.
  • A region of J plants with price 11 * 20 = 220.
  • A region of C plants with price 1 * 4 = 4.
  • A region of E plants with price 13 * 18 = 234.
  • A region of I plants with price 14 * 22 = 308.
  • A region of M plants with price 5 * 12 = 60.
  • A region of S plants with price 3 * 8 = 24.

So, it has a total price of 1930.

What is the total price of fencing all regions on your map?

Iterations: 0
Total Price: 0

The code is fairly complex. A quick overview:

  • Iterate over each position in the map. At each position...
    1. If we've seen this position before, skip it
    2. Use a recursive flood-fill algorithm to get all adjacent positions that make up a region

Once we have each region, we can calculate the number of edges (i.e. the perimiter) for that region. The code for this is very simple. Let's say we have a region that looks like this:

1
2
3
4
5
..... ..A.. .AAA. ..A.. .....

Where the A characters are the positions that make up the region.

To calculate perimiter, we simply:

  • Iterate over each position. At each position...
    1. Start with 0 edges for that position
    2. Check one space above our position. If it's NOT part of the region, edges += 1
    3. Check one space right of our position. If it's NOT part of the region, edges += 1
    4. Check one space below our position. If it's NOT part of the region, edges += 1
    5. Check one space left of our position. If it's NOT part of the region, edges += 1

This gets us the number of edges for a given position. To get the total perimiter for the region, we sum the number of edges for all positions in the region.

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
type StrPosition = `${number},${number}`; interface Position { x: number; y: number; } interface EdgedPosition extends Position { edges: number; } class Region { value: string; positions: Array<EdgedPosition>; edges: number; constructor(value: string, positions: Array<Position>) { this.value = value; // Populate str positions const strPositions = new Set(); positions.forEach(({ y, x }) => strPositions.add(`${y},${x}`)); // Calculate edges this.positions = []; positions.forEach(({ y, x }) => { let positionEdges = 0; // Above const above: StrPosition = `${y - 1},${x}`; if (!strPositions.has(above)) positionEdges += 1; const right: StrPosition = `${y},${x + 1}`; if (!strPositions.has(right)) positionEdges += 1; const below: StrPosition = `${y + 1},${x}`; if (!strPositions.has(below)) positionEdges += 1; const left: StrPosition = `${y},${x - 1}`; if (!strPositions.has(left)) positionEdges += 1; this.positions.push({ y, x, edges: positionEdges }); }); this.edges = sum(this.positions.map(({ edges }) => edges)); } get price() { return this.positions.length * this.edges; } } class Map { matrix: Array<Array<string>>; regions: Array<Region>; constructor(matrix: Array<Array<string>>) { // Poor man's copy this.matrix = JSON.parse(JSON.stringify(matrix)); this.regions = []; // Start figuring out regions const seenPositions = new Set<StrPosition>(); // Recursive function to find regions const findConnectedPositions = (y: number, x: number, value: string) => { const positions: Array<Position> = []; // Above if (!seenPositions.has(`${y - 1},${x}`) && this.at(y - 1, x) === value) { seenPositions.add(`${y - 1},${x}`); positions.push({ y: y - 1, x }); positions.push(...findConnectedPositions(y - 1, x, value)); } // Right if (!seenPositions.has(`${y},${x + 1}`) && this.at(y, x + 1) === value) { seenPositions.add(`${y},${x + 1}`); positions.push({ y, x: x + 1 }); positions.push(...findConnectedPositions(y, x + 1, value)); } // Below if (!seenPositions.has(`${y + 1},${x}`) && this.at(y + 1, x) === value) { seenPositions.add(`${y + 1},${x}`); positions.push({ y: y + 1, x }); positions.push(...findConnectedPositions(y + 1, x, value)); } // Left if (!seenPositions.has(`${y},${x - 1}`) && this.at(y, x - 1) === value) { seenPositions.add(`${y},${x - 1}`); positions.push({ y, x: x - 1 }); positions.push(...findConnectedPositions(y, x - 1, value)); } return positions; }; this.matrix.forEach((row, y) => { row.forEach((character, x) => { const strPosition: StrPosition = `${y},${x}`; if (seenPositions.has(strPosition)) { // Seen this before, skip it return; } seenPositions.add(strPosition); this.regions.push( new Region(character, [{ y, x }, ...findConnectedPositions(y, x, character)]) ); }); }); } at(y: number, x: number) { return this.matrix[y]?.[x]; } }

Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount!

Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is.

Consider this example again:

1
2
3
4
AAAA BBCD BBCC EEEC

The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides!

Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80.

The second example above (full of type X and O plants) would have a total price of 436.

Here's a map that includes an E-shaped region full of type E plants:

1
2
3
4
5
EEEEE EXXXX EEEEE EXXXX EEEEE

The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236.

This map has a total price of 368:

1
2
3
4
5
6
AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA

It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.)

The larger example from before now has the following updated prices:

  • A region of R plants with price 12 * 10 = 120.
  • A region of I plants with price 4 * 4 = 16.
  • A region of C plants with price 14 * 22 = 308.
  • A region of F plants with price 10 * 12 = 120.
  • A region of V plants with price 13 * 10 = 130.
  • A region of J plants with price 11 * 12 = 132.
  • A region of C plants with price 1 * 4 = 4.
  • A region of E plants with price 13 * 8 = 104.
  • A region of I plants with price 14 * 16 = 224.
  • A region of M plants with price 5 * 6 = 30.
  • A region of S plants with price 3 * 6 = 18.

Adding these together produces its new total price of 1206.

What is the new total price of fencing all regions on your map?

The first part of this solution (i.e. finding regions) is identical to Part 1.

The second part (i.e. calculating sides) is a bit more complex. We'll first calculate all edges in the region and include information on what side of the node that edge is on.

  • Iterate over all edges in the region. For each edge...
    1. If we've seen this edge before, skip it
    2. Increment the number of sides we've seen so far (seeing a new edge here always counts as a new side)
    3. Iterate over all edges in the region, accumulating adjacent edges (i.e. edges that have the same side and are one-hop away (either x ± 1 or y ± 1)
  • Once we stop accumulating adjacent edges (we've found all adjacent edges for a side), mark those edges as seen

In this way, we accumulate edges into sides such that every edge is checked against every side for a possible match.

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
type StrPosition = `${number},${number}`; interface Position { x: number; y: number; } type Side = "above" | "right" | "below" | "left"; type StrEdge = `${number},${number},${Side}`; interface Edge extends Position { side: Side; } function adjacent(edge1: Edge, edge2: Edge) { if (edge2.side !== edge1.side) return false; // Above if (edge2.y === edge1.y - 1 && edge2.x === edge1.x) return true; // Right if (edge2.y === edge1.y && edge2.x === edge1.x + 1) return true; // Below if (edge2.y === edge1.y + 1 && edge2.x === edge1.x) return true; // Left if (edge2.y === edge1.y && edge2.x === edge1.x - 1) return true; return false; } class Region { value: string; positions: Array<Position>; edges: Array<Edge>; sides: number; constructor(value: string, positions: Array<Position>) { this.value = value; // Populate str positions const strPositions = new Set(); positions.forEach(({ y, x }) => strPositions.add(`${y},${x}`)); // Calculate edges this.positions = []; this.edges = []; positions.forEach(({ y, x }) => { let positionEdges = 0; // Above const above: StrPosition = `${y - 1},${x}`; if (!strPositions.has(above)) { positionEdges += 1; this.edges.push({ y, x, side: "above" }); } const right: StrPosition = `${y},${x + 1}`; if (!strPositions.has(right)) { positionEdges += 1; this.edges.push({ y, x, side: "right" }); } const below: StrPosition = `${y + 1},${x}`; if (!strPositions.has(below)) { positionEdges += 1; this.edges.push({ y, x, side: "below" }); } const left: StrPosition = `${y},${x - 1}`; if (!strPositions.has(left)) { positionEdges += 1; this.edges.push({ y, x, side: "left" }); } this.positions.push({ y, x }); }); // Calculate sides this.sides = 0; const seenEdges = new Set<StrEdge>(); for (let i = 0; i < this.edges.length; i++) { const edge = this.edges[i]!; // Skip edges we've already seen if (seenEdges.has(`${edge.y},${edge.x},${edge.side}`)) continue; seenEdges.add(`${edge.y},${edge.x},${edge.side}`); const side: Array<Edge> = [edge]; this.sides += 1; while (true) { // Save number of edges on this side for this loop const start = side.length; // Get all adjacent edges const adjacentEdges = this.edges.filter((adjacentEdge) => { return side.some((sideEdge) => adjacent(sideEdge, adjacentEdge)); }); // Combine with seen edges and side adjacentEdges.forEach((adjacentEdge) => { if (seenEdges.has(`${adjacentEdge.y},${adjacentEdge.x},${adjacentEdge.side}`)) return; seenEdges.add(`${adjacentEdge.y},${adjacentEdge.x},${adjacentEdge.side}`); side.push(adjacentEdge); }); const end = side.length; if (start === end) break; } } } get price() { return this.positions.length * this.sides; } } class Map { matrix: Array<Array<string>>; regions: Array<Region>; constructor(matrix: Array<Array<string>>) { // Poor man's copy this.matrix = JSON.parse(JSON.stringify(matrix)); this.regions = []; // Start figuring out regions const seenPositions = new Set<StrPosition>(); // Recursive function to find regions const findConnectedPositions = (y: number, x: number, value: string) => { const positions: Array<Position> = []; // Above if (!seenPositions.has(`${y - 1},${x}`) && this.at(y - 1, x) === value) { seenPositions.add(`${y - 1},${x}`); positions.push({ y: y - 1, x }); positions.push(...findConnectedPositions(y - 1, x, value)); } // Right if (!seenPositions.has(`${y},${x + 1}`) && this.at(y, x + 1) === value) { seenPositions.add(`${y},${x + 1}`); positions.push({ y, x: x + 1 }); positions.push(...findConnectedPositions(y, x + 1, value)); } // Below if (!seenPositions.has(`${y + 1},${x}`) && this.at(y + 1, x) === value) { seenPositions.add(`${y + 1},${x}`); positions.push({ y: y + 1, x }); positions.push(...findConnectedPositions(y + 1, x, value)); } // Left if (!seenPositions.has(`${y},${x - 1}`) && this.at(y, x - 1) === value) { seenPositions.add(`${y},${x - 1}`); positions.push({ y, x: x - 1 }); positions.push(...findConnectedPositions(y, x - 1, value)); } return positions; }; this.matrix.forEach((row, y) => { row.forEach((character, x) => { const strPosition: StrPosition = `${y},${x}`; if (seenPositions.has(strPosition)) { // Seen this before, skip it return; } seenPositions.add(strPosition); this.regions.push( new Region(character, [{ y, x }, ...findConnectedPositions(y, x, character)]) ); }); }); } at(y: number, x: number) { return this.matrix[y]?.[x]; } }
Part 1 TimePart 1 RankPart 2 TimePart 2 Rank
01:03:166,62701:44:103,769

I was really hoping I could get away without doing a flood-fill algorithm, but I gave in after ~30 minutes or so. This was a pretty satisfying one to solve, but I can tell the challenges are starting to get much harder.