Advertisement
mgla

Advent of Code - 2024 - Day 10

Dec 9th, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. var input = await File.ReadAllLinesAsync("input.txt");
  2.  
  3. var gridSize = input.Length;
  4. var nodes = new Node[gridSize, gridSize];
  5. var trailHeads = new List<Node>();
  6.  
  7. for (var row = 0; row < gridSize; row++)
  8. {
  9.     for (var col = 0; col < gridSize; col++)
  10.     {
  11.         nodes[row, col] = new Node(input[row][col] - '0', []);
  12.     }
  13. }
  14.  
  15. for (var row = 0; row < gridSize; row++)
  16. {
  17.     for (var col = 0; col < gridSize; col++)
  18.     {
  19.         var node = nodes[row, col];
  20.         var next = node.Value + 1;
  21.  
  22.         if (row > 0 && nodes[row - 1, col].Value == next)
  23.         {
  24.             node.Neighbors.Add(nodes[row - 1, col]);
  25.         }
  26.  
  27.         if (col > 0 && nodes[row, col - 1].Value == next)
  28.         {
  29.             node.Neighbors.Add(nodes[row, col - 1]);
  30.         }
  31.  
  32.         if (row < gridSize - 1 && nodes[row + 1, col].Value == next)
  33.         {
  34.             node.Neighbors.Add(nodes[row + 1, col]);
  35.         }
  36.  
  37.         if (col < gridSize - 1 && nodes[row, col + 1].Value == next)
  38.         {
  39.             node.Neighbors.Add(nodes[row, col + 1]);
  40.         }
  41.  
  42.         if (node.Value == 0)
  43.         {
  44.             trailHeads.Add(node);
  45.         }
  46.     }
  47. }
  48.  
  49. Console.WriteLine($"Part 1: {WalkTrails(true)}");
  50. Console.WriteLine($"Part 2: {WalkTrails(false)}");
  51.  
  52. return;
  53.  
  54. int WalkTrails(bool part1)
  55. {
  56.     var result = 0;
  57.     foreach (var trailHead in trailHeads)
  58.     {
  59.         //DFS
  60.         var stack = new Stack<Node>();
  61.         stack.Push(trailHead);
  62.         var visited = new HashSet<Node>();
  63.  
  64.         while (stack.Count > 0)
  65.         {
  66.             var current = stack.Pop();
  67.            
  68.             if (part1 && !visited.Add(current))
  69.             {
  70.                 continue; //Part 1: We only count each node once.
  71.             }
  72.  
  73.             if (current.Value == 9)
  74.             {
  75.                 result++;
  76.                 continue;
  77.             }
  78.            
  79.             foreach (var neighbor in current.Neighbors)
  80.             {
  81.                 stack.Push(neighbor);
  82.             }
  83.         }
  84.     }
  85.  
  86.     return result;
  87. }
  88.  
  89. internal record Node(int Value, List<Node> Neighbors);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement