From 2427e955b55d0c367ad0b5137182336e572be6fd Mon Sep 17 00:00:00 2001 From: timmoth Date: Sun, 16 Jun 2024 19:43:10 +0100 Subject: [PATCH] Djikstras uses priority queue --- DsaDotnet/Search/Dijkstra.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/DsaDotnet/Search/Dijkstra.cs b/DsaDotnet/Search/Dijkstra.cs index 3b63352..d8f7638 100644 --- a/DsaDotnet/Search/Dijkstra.cs +++ b/DsaDotnet/Search/Dijkstra.cs @@ -30,7 +30,7 @@ public static partial class Search var distances = new Dictionary, int>(); var previous = new Dictionary, WeightedGraphNode>(); - var priorityQueue = new SortedDictionary>(); // Stores nodes by distance + var priorityQueue = new PriorityQueue, int>(); // Stores nodes by distance WeightedGraphNode? endNode = null; // Set distance to each node as the maximum @@ -51,24 +51,23 @@ public static partial class Search // Distance to the start node is 0. distances[startNode] = 0; - priorityQueue[0] = startNode; + priorityQueue.Enqueue(startNode, 0); while (priorityQueue.Count > 0) { - var current = priorityQueue.First(); - priorityQueue.Remove(current.Key); + var current = priorityQueue.Dequeue(); - foreach (var (weight, neighbor) in current.Value.GetWeightedNeighbors()) + foreach (var (weight, neighbor) in current.GetWeightedNeighbors()) { - var newDistance = distances[current.Value] + weight; + var newDistance = distances[current] + weight; if (newDistance >= distances[neighbor]) { continue; } distances[neighbor] = newDistance; - previous[neighbor] = current.Value; - priorityQueue[newDistance] = neighbor; + previous[neighbor] = current; + priorityQueue.Enqueue(neighbor, newDistance); } }