-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay12.cs
More file actions
101 lines (84 loc) · 2.74 KB
/
Day12.cs
File metadata and controls
101 lines (84 loc) · 2.74 KB
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
namespace aoc.y2024;
using Position = (int, int);
[RunnableDay(year: 2024, day: 12)]
class Day12 : Day
{
public override string PartOne()
{
var input = ReadInputLines();
char[][] garden = new char[input.Length][];
var plotsMap = new Dictionary<Position, char>();
for (var y = 0; y < input.Length; y++)
{
garden[y] = [.. input[y]];
for (var x = 0; x < garden[y].Length; x++)
{
plotsMap[(x, y)] = garden[y][x];
}
}
List<Dictionary<Position, int>> regions = [];
while (plotsMap.Count > 0)
{
Dictionary<Position, int> region = [];
var currentPos = plotsMap.First().Key;
plotsMap.Remove(currentPos);
var currentType = garden[currentPos.Item2][currentPos.Item1];
region.Add(currentPos, currentType);
Stack<Position> frontier = [];
frontier.Push(currentPos);
while (frontier.Count > 0)
{
var position = frontier.Pop();
var fences = 0;
foreach (var direction in Directions())
{
var neighbor = direction.Move(position);
if (region.ContainsKey(neighbor)) continue;
if (!WithinBounds(garden, neighbor))
{
fences++;
continue;
}
;
if (currentType == garden[neighbor.Item2][neighbor.Item1])
{
region.Add(neighbor, 0);
frontier.Push(neighbor);
plotsMap.Remove(neighbor);
}
else
{
fences++;
}
}
region[position] = fences;
}
regions.Add(region);
}
var total = 0;
foreach (var area in regions)
{
total += area.Count * area.Values.Sum();
}
return total.ToString();
}
public override string PartTwo()
{
return "-";
}
// TODO: Move this to a shared place since is used by day 10 as well
private static Direction[] Directions()
{
return [
Direction.Up,
Direction.Right,
Direction.Down,
Direction.Left,
];
}
// TODO: Move this to a shared place since is used by day 10 as well
private static bool WithinBounds(char[][] map, Position position)
{
return position.Item1 >= 0 && position.Item1 < map[0].Length && position.Item2 >= 0 && position.Item2 < map.Length;
}
}