-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay10.cs
More file actions
114 lines (93 loc) · 2.91 KB
/
Day10.cs
File metadata and controls
114 lines (93 loc) · 2.91 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq.Expressions;
using _2024.Utils;
using System.Threading.Tasks;
namespace _2024._10;
public class Day10 : Base
{
public Day10(bool example) : base(example)
{
Day = "10";
}
private int[][] Map { get; set; }
private HashSet<ValueTuple<int, int>> TrailEnds = [];
private readonly ValueTuple<int, int>[] Directions =
[
(0, 1),
(0, -1),
(1, 0),
(-1, 0)
];
private void PrintMap(){
foreach ((int[] line, int row) in Map.Enumerate())
{
foreach ((int height, int col) in line.Enumerate())
{
Console.Write(height);
}
Console.WriteLine();
}
Console.WriteLine();}
private int SearchPaths(ValueTuple<int, int> position, HashSet<ValueTuple<int, int>> visited)
{
if (!visited.Add(position))
{
return 0;
}
if (Map[position.Item1][position.Item2] == 9)
{
TrailEnds.Add(position);
return 1;
}
int paths = 0;
foreach ((int row, int col) in Directions)
{
ValueTuple<int, int> newPosition = (position.Item1+row, position.Item2+col);
if (newPosition.Item1 < 0 || newPosition.Item1 >= Map.Length || newPosition.Item2 < 0 ||
newPosition.Item2 >= Map[newPosition.Item1].Length)
{
continue;
}
if (Map[position.Item1][position.Item2] + 1 != Map[newPosition.Item1][newPosition.Item2])
{
continue;
}
paths += SearchPaths(newPosition, [..visited]);
}
return paths;
}
private int SolvePuzzle(bool example, int stage)
{
string[] input = ReadInput();
Map = new int[input.Length][];
for (int row = 0; row < input.Length; row++)
{
Map[row] = input[row].ToCharArray().Select(c => int.Parse(c.ToString())).ToArray();
}
int score = 0;
foreach ((int[] row, int rowIdx) in Map.Enumerate())
{
foreach ((int height, int col) in row.Enumerate())
{
if (height != 0)
{
continue;
}
int uniquePaths = SearchPaths((rowIdx, col), []);
score += stage == 1 ? (TrailEnds.Count) : (uniquePaths);
TrailEnds.Clear();
}
}
return score;
}
public override object PartOne()
{
return SolvePuzzle(Example, 1);
}
public override object PartTwo()
{
return SolvePuzzle(Example, 2);
}
}