Program.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. namespace D13._1
  5. {
  6. class Program
  7. {
  8. static bool IsOpenSpace((int x, int y) coord, int fav)
  9. {
  10. var n = (coord.x * coord.x) + (3 * coord.x) + (2 * coord.x * coord.y) + coord.y + (coord.y * coord.y) + fav;
  11. int nbits = 0;
  12. while (n > 0)
  13. {
  14. nbits += n & 1;
  15. n >>= 1;
  16. }
  17. return nbits % 2 == 0;
  18. }
  19. static readonly (int mx, int my)[] Moves = new[] { (-1, 0), (0, -1), (1, 0), (0, 1) };
  20. static int SolveMaze((int x, int y) start, int goal, int fav)
  21. {
  22. int answer = 0;
  23. var queue = new Queue<((int x, int y), int step)>();
  24. var visited = new HashSet<(int, int)>();
  25. queue.Enqueue((start, 0));
  26. while (queue.Count > 0)
  27. {
  28. ((int x, int y) coord, int step) = queue.Dequeue();
  29. if (step == goal) continue;
  30. answer++;
  31. foreach (var (mx, my) in Moves)
  32. {
  33. (int x, int y) ncoord = (coord.x + mx, coord.y + my);
  34. if (ncoord.x < 0 || ncoord.y < 0) continue;
  35. if (IsOpenSpace(ncoord, fav) == false) continue;
  36. if (visited.Contains(ncoord) == true) continue;
  37. visited.Add(ncoord);
  38. queue.Enqueue((ncoord, step + 1));
  39. }
  40. }
  41. return answer;
  42. }
  43. static void Main(string[] args)
  44. {
  45. var sw = Stopwatch.StartNew();
  46. var answer = SolveMaze((1, 1), 50, int.Parse(args[0]));
  47. Console.WriteLine($"The answer is : {answer}\n");
  48. sw.Stop();
  49. Console.WriteLine($"Execution time : {sw.ElapsedMilliseconds}ms");
  50. }
  51. }
  52. }