Map.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. namespace Day17;
  2. public class Map
  3. {
  4. private readonly Tile[,] _tiles;
  5. private readonly int _width;
  6. private readonly int _height;
  7. public Map(Tile[,] tiles, int width, int height)
  8. {
  9. _tiles = tiles;
  10. _width = width;
  11. _height = height;
  12. }
  13. public void Print()
  14. {
  15. for (var y = 0; y < _height; y++)
  16. {
  17. for (var x = 0; x < _width; x++)
  18. {
  19. Console.Write(_tiles[x, y].Display);
  20. }
  21. Console.WriteLine();
  22. }
  23. Console.WriteLine();
  24. }
  25. public int ShortestPath()
  26. {
  27. var n = 0;
  28. var goal = _tiles[_width - 1, _height - 1];
  29. var visited = new HashSet<string>();
  30. var queue = new PriorityQueue<Path, int>();
  31. queue.Enqueue(new Path(null, _tiles[0, 0], new Vec(1, 0)), 0);
  32. queue.Enqueue(new Path(null, _tiles[0, 0], new Vec(0, 1)), 0);
  33. while (queue.Count > 0)
  34. {
  35. var current = queue.Dequeue();
  36. var curKey = current.GetKey();
  37. if (!visited.Add(curKey))
  38. {
  39. continue;
  40. }
  41. foreach (var v in current.Next())
  42. {
  43. var pos = current.Tile.Position.Add(v);
  44. if (IsValid(pos))
  45. {
  46. var next = new Path(current, Tile(pos), v);
  47. if (next.Tile == goal)
  48. {
  49. var cost = Backtrack(next);
  50. return cost;
  51. }
  52. queue.Enqueue(next, next.Cost);
  53. }
  54. }
  55. if (n % 100 == 0)
  56. {
  57. Console.WriteLine($"Queue: {queue.Count}");
  58. }
  59. n++;
  60. }
  61. return -1;
  62. }
  63. private int Backtrack(Path path)
  64. {
  65. var sum = 0;
  66. while (path.Prev != null)
  67. {
  68. sum += path.Tile.Cost;
  69. path.Tile.SetDisplay(path.VRun.Arrow());
  70. path = path.Prev;
  71. }
  72. return sum;
  73. }
  74. private bool IsValid(Vec position)
  75. {
  76. return position.X >= 0 && position.X < _width && position.Y >= 0 && position.Y < _height;
  77. }
  78. private Tile Tile(Vec position)
  79. {
  80. return _tiles[position.X, position.Y];
  81. }
  82. }