| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- namespace D19._2
- {
- class Program
- {
- static void Main(string[] args)
- {
- if (args.Length < 1) throw new ArgumentException();
- if (File.Exists(args[0]) == false) throw new FileNotFoundException();
- string input;
- List<(string, string)> replacements;
- _1.Program.ParseFile(args, out input, out replacements);
- replacements = replacements.Select(r => (r.Item2, r.Item1)).ToList();
- var steps = TestMolecules(input, "e", replacements);
- Console.WriteLine($"The answer is : {steps}");
- }
- private static void ParseFile(string[] args, out string input, out List<(string, string)> replacements)
- {
- input = string.Empty;
- replacements = new List<(string, string)>();
- using (var file = File.OpenText(args[0]))
- {
- while (true)
- {
- var line = file.ReadLine();
- if (line == null) break;
- if (line == string.Empty) continue;
- var lr = line.Split(" => ");
- if (lr.Length == 2) replacements.Add((lr[0], lr[1]));
- else input = lr[0];
- }
- }
- }
- private static int TestMolecules(string input, string find, List<(string, string)> replacements)
- {
- var tested = new HashSet<string>();
- var buildQueue = new List<(string molecule, int step)>();
- buildQueue.Add((input, 0));
- while (buildQueue.Count > 0)
- {
- (var mol, int step) = buildQueue.ElementAt(0);
- buildQueue.RemoveAt(0);
- input = mol;
- tested.Add(input);
- if (input == find) return step;
- foreach (var molecule in _1.Program.TestMolecules(input, replacements).OrderByDescending(s => s.Length))
- {
- if (tested.Contains(molecule) == false)
- buildQueue.Insert(0, (molecule, step + 1));
- }
- }
- return 0;
- }
- }
- }
|