Program.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace D17._2
  6. {
  7. class Program
  8. {
  9. static byte[] ToB(string str) => Encoding.ASCII.GetBytes(str);
  10. static string ToS(byte[] b) => BitConverter.ToString(b).Replace("-", "");
  11. private static string GetHash(string input, string sequence, MD5 md5) => ToS(md5.ComputeHash(ToB($"{input}{sequence}")));
  12. static string SolveMaze((int x, int y) coord, (int x, int y) goal, string input)
  13. {
  14. var queue = new Queue<((int x, int y) coord, string sequence)>();
  15. string sequence = null;
  16. queue.Enqueue((coord, ""));
  17. var longest = "";
  18. var md5 = MD5.Create();
  19. while (queue.Count > 0)
  20. {
  21. var element = queue.Dequeue();
  22. coord = element.coord;
  23. sequence = element.sequence;
  24. if (coord == (3, 3))
  25. {
  26. if (sequence.Length > longest.Length) longest = sequence;
  27. continue;
  28. }
  29. var hash = GetHash(input, sequence, md5);
  30. for (int i = 0; i < 4; i++)
  31. {
  32. if (hash[i] <= 'A') continue;
  33. (int mx, int my) = MoveSequence[i];
  34. (int x, int y) ncoord = (coord.x + mx, coord.y + my);
  35. if (ncoord.x < 0 || ncoord.y < 0 || ncoord.x > 3 || ncoord.y > 3)
  36. continue;
  37. var nsequence = sequence + DoorSequence[i];
  38. queue.Enqueue((ncoord, nsequence));
  39. }
  40. }
  41. md5.Dispose();
  42. return longest;
  43. }
  44. static readonly char[] DoorSequence = new[] { 'U', 'D', 'L', 'R' };
  45. static readonly (int mx, int my)[] MoveSequence = new[] { (0, -1), (0, 1), (-1, 0), (1, 0) };
  46. static void Main(string[] args)
  47. {
  48. var seq = SolveMaze((0, 0), (3, 3), args[0]);
  49. Console.WriteLine($"Longest sequence size is : {seq.Length}");
  50. }
  51. }
  52. }