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:
1234AAAA
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:
12345678910111213+-+-+-+-+
|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:
12345OOOOO
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:
12345678910RRRRIICCFF
RRRRIICCCF
VVRRRCCFFF
VVRCCCJFFF
VVVVCJJCFE
VVIVCCJJEE
VVIIICJJEE
MIIIIIJJEE
MIIISIJEEE
MMMISSJEEE
It contains:
- A region of
R
plants with price12 * 18 = 216
. - A region of
I
plants with price4 * 8 = 32
. - A region of
C
plants with price14 * 28 = 392
. - A region of
F
plants with price10 * 18 = 180
. - A region of
V
plants with price13 * 20 = 260
. - A region of
J
plants with price11 * 20 = 220
. - A region of
C
plants with price1 * 4 = 4
. - A region of
E
plants with price13 * 18 = 234
. - A region of
I
plants with price14 * 22 = 308
. - A region of
M
plants with price5 * 12 = 60
. - A region of
S
plants with price3 * 8 = 24
.
So, it has a total price of 1930
.
What is the total price of fencing all regions on your map?
The code is fairly complex. A quick overview:
- Iterate over each position in the map. At each position...
- If we've seen this position before, skip it
- 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:
12345.....
..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...
- Start with
0
edges for that position - Check one space above our position. If it's NOT part of the region,
edges += 1
- Check one space right of our position. If it's NOT part of the region,
edges += 1
- Check one space below our position. If it's NOT part of the region,
edges += 1
- Check one space left of our position. If it's NOT part of the region,
edges += 1
- Start with
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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124type 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:
1234AAAA
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:
12345EEEEE
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
:
123456AAAAAA
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 price12 * 10 = 120
. - A region of
I
plants with price4 * 4 = 16
. - A region of
C
plants with price14 * 22 = 308
. - A region of
F
plants with price10 * 12 = 120
. - A region of
V
plants with price13 * 10 = 130
. - A region of
J
plants with price11 * 12 = 132
. - A region of
C
plants with price1 * 4 = 4
. - A region of
E
plants with price13 * 8 = 104
. - A region of
I
plants with price14 * 16 = 224
. - A region of
M
plants with price5 * 6 = 30
. - A region of
S
plants with price3 * 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...
- If we've seen this edge before, skip it
- Increment the number of sides we've seen so far (seeing a new edge here always counts as a new side)
- 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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196type 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 Time | Part 1 Rank | Part 2 Time | Part 2 Rank |
---|---|---|---|
01:03:16 | 6,627 | 01:44:10 | 3,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.