Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = await File.ReadAllLinesAsync("input.txt");
- var gridSize = input.Length;
- var nodes = new Node[gridSize, gridSize];
- var trailHeads = new List<Node>();
- for (var row = 0; row < gridSize; row++)
- {
- for (var col = 0; col < gridSize; col++)
- {
- nodes[row, col] = new Node(input[row][col] - '0', []);
- }
- }
- for (var row = 0; row < gridSize; row++)
- {
- for (var col = 0; col < gridSize; col++)
- {
- var node = nodes[row, col];
- var next = node.Value + 1;
- if (row > 0 && nodes[row - 1, col].Value == next)
- {
- node.Neighbors.Add(nodes[row - 1, col]);
- }
- if (col > 0 && nodes[row, col - 1].Value == next)
- {
- node.Neighbors.Add(nodes[row, col - 1]);
- }
- if (row < gridSize - 1 && nodes[row + 1, col].Value == next)
- {
- node.Neighbors.Add(nodes[row + 1, col]);
- }
- if (col < gridSize - 1 && nodes[row, col + 1].Value == next)
- {
- node.Neighbors.Add(nodes[row, col + 1]);
- }
- if (node.Value == 0)
- {
- trailHeads.Add(node);
- }
- }
- }
- Console.WriteLine($"Part 1: {WalkTrails(true)}");
- Console.WriteLine($"Part 2: {WalkTrails(false)}");
- return;
- int WalkTrails(bool part1)
- {
- var result = 0;
- foreach (var trailHead in trailHeads)
- {
- //DFS
- var stack = new Stack<Node>();
- stack.Push(trailHead);
- var visited = new HashSet<Node>();
- while (stack.Count > 0)
- {
- var current = stack.Pop();
- if (part1 && !visited.Add(current))
- {
- continue; //Part 1: We only count each node once.
- }
- if (current.Value == 9)
- {
- result++;
- continue;
- }
- foreach (var neighbor in current.Neighbors)
- {
- stack.Push(neighbor);
- }
- }
- }
- return result;
- }
- internal record Node(int Value, List<Node> Neighbors);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement