-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay6.cs
95 lines (75 loc) · 3.01 KB
/
Day6.cs
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
using Aoc2024Net.Utilities;
namespace Aoc2024Net.Days
{
internal sealed class Day6 : Day
{
private const char GuardSymbol = '^';
private const char QbstructionSymbol = '#';
private const char EmptySpaceSymbol = '.';
private static readonly Dictionary<Coordinate, Coordinate> Turns = new()
{
[new Coordinate(0, 1)] = new Coordinate(-1, 0),
[new Coordinate(0, -1)] = new Coordinate(1, 0),
[new Coordinate(1, 0)] = new Coordinate(0, 1),
[new Coordinate(-1, 0)] = new Coordinate(0, -1),
};
public override object? SolvePart1()
{
var (grid, width, height) = InputData.GetInputCharGrid();
var coordinates = GridUtilities.GetAllCoordinates(grid);
var direction = new Coordinate(0, -1);
var position = coordinates.First(c => grid.At(c) == GuardSymbol);
var visitedPositions = new HashSet<Coordinate> { position };
while (true)
{
var nextPosition = position + direction;
if (!grid.IsInGrid(width, height, nextPosition))
break;
if (grid.At(nextPosition) == QbstructionSymbol)
{
direction = Turns[direction];
continue;
}
visitedPositions.Add(nextPosition);
position = nextPosition;
}
return visitedPositions.Count;
}
public override object? SolvePart2()
{
var (grid, width, height) = InputData.GetInputCharGrid();
var coordinates = GridUtilities.GetAllCoordinates(grid);
var startDirection = new Coordinate(0, -1);
var startPosition = coordinates.First(c => grid.At(c) == GuardSymbol);
var result = 0;
foreach (var coordinate in coordinates)
{
if (grid.At(coordinate) != EmptySpaceSymbol)
continue;
grid.SetAt(coordinate, QbstructionSymbol);
var direction = startDirection;
var position = startPosition;
var visitedVectors = new HashSet<Vector> { new (position, direction) };
while (true)
{
var nextPosition = position + direction;
if (!grid.IsInGrid(width, height, nextPosition))
break;
if (grid.At(nextPosition) == QbstructionSymbol)
{
direction = Turns[direction];
continue;
}
if (!visitedVectors.Add(new (nextPosition, direction)))
{
result++;
break;
}
position = nextPosition;
}
grid.SetAt(coordinate, EmptySpaceSymbol);
}
return result;
}
}
}