Program.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D19._2
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. if (args.Length < 1) throw new ArgumentException();
  12. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  13. string input;
  14. List<(string, string)> replacements;
  15. _1.Program.ParseFile(args, out input, out replacements);
  16. replacements = replacements.Select(r => (r.Item2, r.Item1)).ToList();
  17. var steps = TestMolecules(input, "e", replacements);
  18. Console.WriteLine($"The answer is : {steps}");
  19. }
  20. private static void ParseFile(string[] args, out string input, out List<(string, string)> replacements)
  21. {
  22. input = string.Empty;
  23. replacements = new List<(string, string)>();
  24. using (var file = File.OpenText(args[0]))
  25. {
  26. while (true)
  27. {
  28. var line = file.ReadLine();
  29. if (line == null) break;
  30. if (line == string.Empty) continue;
  31. var lr = line.Split(" => ");
  32. if (lr.Length == 2) replacements.Add((lr[0], lr[1]));
  33. else input = lr[0];
  34. }
  35. }
  36. }
  37. private static int TestMolecules(string input, string find, List<(string, string)> replacements)
  38. {
  39. var tested = new HashSet<string>();
  40. var buildQueue = new List<(string molecule, int step)>();
  41. buildQueue.Add((input, 0));
  42. while (buildQueue.Count > 0)
  43. {
  44. (var mol, int step) = buildQueue.ElementAt(0);
  45. buildQueue.RemoveAt(0);
  46. input = mol;
  47. tested.Add(input);
  48. if (input == find) return step;
  49. foreach (var molecule in _1.Program.TestMolecules(input, replacements).OrderByDescending(s => s.Length))
  50. {
  51. if (tested.Contains(molecule) == false)
  52. buildQueue.Insert(0, (molecule, step + 1));
  53. }
  54. }
  55. return 0;
  56. }
  57. }
  58. }