Advertisement
mgla

Advent of Code 2023 - Day 25

Dec 25th, 2023 (edited)
1,147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1. using System.Text;
  2.  
  3. var input = File.ReadAllLines("input.txt");
  4.  
  5. // We will generate a GraphViz file (*.dot) to visualize the graph and identify the edges that have to be removed.
  6. var dotFile = new StringBuilder();
  7. dotFile.AppendLine("graph {");
  8.  
  9. var wires = new Dictionary<string, HashSet<string>>();
  10. foreach (var line in input)
  11. {
  12.     var parts = line.Split(": ");
  13.     var wire = parts[0].Trim();
  14.     var connections = parts[1].Trim().Split(" ").ToList();
  15.  
  16.     if (!wires.ContainsKey(wire))
  17.     {
  18.         wires[wire] = [];
  19.     }
  20.    
  21.     foreach (var connection in connections)
  22.     {
  23.         // Generate content for a GraphViz graph.
  24.         dotFile.AppendLine($"    {wire} -- {connection}");
  25.  
  26.         if (!wires.ContainsKey(connection))
  27.         {
  28.             wires[connection] = [];
  29.         }
  30.  
  31.         wires[wire].Add(connection);
  32.         wires[connection].Add(wire);
  33.     }
  34. }
  35.  
  36. dotFile.AppendLine("}");
  37. File.WriteAllText("graph.dot", dotFile.ToString());
  38.  
  39. // I used Gephi (https://gephi.org/) to visualize the graph and identify the edges that have to be removed.
  40. // I used the "Force Atlas" layout algorithm to get a nice layout of the graph.
  41. // Here are the edges that had to be removed for my input:
  42.  
  43. const string a1 = "cbl";
  44. const string b1 = "vmq";
  45.  
  46. const string a2 = "bvz";
  47. const string b2 = "nvf";
  48.  
  49. const string a3 = "klk";
  50. const string b3 = "xgz";
  51.  
  52. wires[a1].Remove(b1);
  53. wires[b1].Remove(a1);
  54.  
  55. wires[a2].Remove(b2);
  56. wires[b2].Remove(a2);
  57.  
  58. wires[a3].Remove(b3);
  59. wires[b3].Remove(a3);
  60.  
  61. // Now we just need to use BFS to count the number of reachable nodes from a random single node of the removed pairs
  62.  
  63. var visited = new HashSet<string>();
  64. var queue = new Queue<string>();
  65. queue.Enqueue(a1);
  66.  
  67. while (queue.Count > 0)
  68. {
  69.     var current = queue.Dequeue();
  70.  
  71.     if (!visited.Add(current))
  72.     {
  73.         continue;
  74.     }
  75.  
  76.     foreach (var connection in wires[current])
  77.     {
  78.         queue.Enqueue(connection);
  79.     }
  80. }
  81.  
  82. // We have the size of one of the two subsets, so we can calculate the size other subset by subtracting the first's
  83. // size from the total number of nodes.
  84.  
  85. Console.Write($"Part 1: {visited.Count * (wires.Count - visited.Count)}");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement