Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Greedy.Architecture;
  7. using System.Drawing;
  8.  
  9. namespace Greedy
  10. {
  11. public class DijkstraData
  12. {
  13. public Point Previous { get; set; }
  14. public int Price { get; set; }
  15. }
  16. public class DijkstraPathFinder
  17. {
  18. public IEnumerable<PathWithCost> GetPathsByDijkstra(State state, Point start,
  19. IEnumerable<Point> targets)
  20. {
  21. var notVisited = new List<Point>();
  22. for (int i = 0; i < state.MapWidth; i++)
  23. for (int j = 0; j < state.MapHeight; j++)
  24. {
  25. notVisited.Add(new Point(i, j));
  26. }
  27. var track = new Dictionary<Point, DijkstraData>();
  28. track[start] = new DijkstraData { Previous = new Point(-100,-100), Price = 0 };
  29. while (true)
  30. {
  31. Point toOpen = new Point(-100, -100);
  32. var bestPrice = int.MaxValue;
  33. foreach (var e in notVisited)
  34. {
  35. if (track.ContainsKey(e) && track[e].Price < bestPrice)
  36. {
  37. bestPrice = track[e].Price;
  38. toOpen = e;
  39. }
  40. }
  41. if (toOpen == new Point(-100, -100)) yield break;
  42. if (targets.Count() == 0) yield break;
  43. for (var dy = -1; dy <= 1; dy++)
  44. for (var dx = -1; dx <= 1; dx++)
  45. {
  46. if ((dx != 0 && dy != 0) && (dx == 0 && dy == 0)) continue; //1
  47. var nextPoint = new Point(toOpen.X + dx, toOpen.Y + dy);
  48. if (!state.InsideMap(nextPoint) && state.IsWallAt(nextPoint)) continue;//2
  49. track.Add(nextPoint, new DijkstraData { Previous = toOpen, Price = state.CellCost[nextPoint.X, nextPoint.Y] + track[toOpen].Price });
  50. }
  51. notVisited.Remove(toOpen);
  52. }
  53. foreach(var target in targets)
  54. {
  55. if(track.ContainsKey(target))
  56. var result = new List<Point>();
  57. while (toOpen != null)
  58. {
  59. result.Add(toOpen);
  60. toOpen = track[toOpen].Previous;
  61. yield return new PathWithCost(bestPrice, result.Reverse());
  62. }
  63. }
  64.  
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement