Ameisen

Untitled

Feb 9th, 2022
1,456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. private static List<string>? Dijkstra(GameLocation start, GameLocation end, Dictionary<string, GameLocation?> locations) {
  2.     try {
  3.         var queue = new SimplePriorityQueue<GameLocation, int>((x, y) => x - y);
  4.         var previous = new Dictionary<GameLocation, GameLocation?>(Game1.locations.Count);
  5.  
  6.         queue.Enqueue(start, 0);
  7.         foreach (var location in Game1.locations) {
  8.             if (previous.TryAdd(location, null)) {
  9.                 queue.EnqueueWithoutDuplicates(location, int.MaxValue);
  10.             }
  11.         }
  12.  
  13.         while (queue.Count != 0) {
  14.             var distance = queue.GetPriority(queue.First);
  15.             var location = queue.Dequeue();
  16.  
  17.             if (distance == int.MaxValue) {
  18.                 return null; // No path
  19.             }
  20.  
  21.             if (location == end) {
  22.                 var result = new List<string>(distance + 1);
  23.  
  24.                 GameLocation? current = location;
  25.                 while (current is not null) {
  26.                     result.Add(current.Name);
  27.                     current = previous.GetValueOrDefault(current, null);
  28.                 }
  29.                 result.Reverse();
  30.                 return result;
  31.             }
  32.  
  33.             void ProcessNeighbor(GameLocation node) {
  34.                 if (!queue!.Contains(node)) {
  35.                     return;
  36.                 }
  37.  
  38.                 var nodeDistance = distance + 1;
  39.                 if (nodeDistance < queue.GetPriority(node)) {
  40.                     previous![node] = location;
  41.                     queue.UpdatePriority(node, nodeDistance);
  42.                 }
  43.             }
  44.  
  45.             foreach (var warp in location.warps) {
  46.                 var neighbor = warp.GetTarget(locations);
  47.                 if (neighbor is null) {
  48.                     continue;
  49.                 }
  50.                 ProcessNeighbor(neighbor);
  51.             }
  52.  
  53.             foreach (var door in location.doors.Pairs) {
  54.                 var neighbor = door.GetTarget(locations);
  55.                 if (neighbor is null) {
  56.                     continue;
  57.                 }
  58.                 ProcessNeighbor(neighbor);
  59.             }
  60.         }
  61.     }
  62.     catch (Exception ex) {
  63.         Debug.Error("Exception generating warp points route list", ex);
  64.     }
  65.  
  66.     return null; // Also no path
  67. }
Advertisement
Add Comment
Please, Sign In to add comment