CodexBloom - Programming Q&A Platform

Difficulty Implementing Dijkstra's Algorithm in C# - Priority Queue Not Returning Expected Shortest Path

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
dijkstra algorithm priority-queue csharp C#

I'm maintaining legacy code that I've hit a wall trying to Hey everyone, I'm running into an issue that's driving me crazy. I'm currently implementing Dijkstra's algorithm in C# to find the shortest paths in a graph, but I'm running into an scenario where my priority queue isn't returning the expected shortest path. I'm using the built-in `SortedSet` for priority queue functionality, but it seems to be giving me incorrect results for certain nodes. Here's a simplified version of my code: ```csharp using System; using System.Collections.Generic; using System.Linq; public class Graph { private Dictionary<int, List<(int, int)>> adj = new Dictionary<int, List<(int, int)>>(); public void AddEdge(int u, int v, int weight) { if (!adj.ContainsKey(u)) adj[u] = new List<(int, int)>(); adj[u].Add((v, weight)); } public Dictionary<int, int> Dijkstra(int start) { var distances = new Dictionary<int, int>(); var priorityQueue = new SortedSet<(int distance, int vertex)>(Comparer<(int, int)>.Create((a, b) => { int comparison = a.distance.CompareTo(b.distance); return comparison == 0 ? a.vertex.CompareTo(b.vertex) : comparison; })); foreach (var vertex in adj.Keys) { distances[vertex] = int.MaxValue; } distances[start] = 0; priorityQueue.Add((0, start)); while (priorityQueue.Count > 0) { var (currentDistance, currentVertex) = priorityQueue.Min; priorityQueue.Remove(priorityQueue.Min); if (currentDistance > distances[currentVertex]) continue; foreach (var (neighbor, weight) in adj[currentVertex]) { int newDist = currentDistance + weight; if (newDist < distances[neighbor]) { distances[neighbor] = newDist; priorityQueue.Add((newDist, neighbor)); } } } return distances; } } ``` When I run this with the following graph setup: ```csharp Graph graph = new Graph(); graph.AddEdge(1, 2, 10); graph.AddEdge(1, 3, 5); graph.AddEdge(2, 3, 2); graph.AddEdge(3, 2, 3); graph.AddEdge(2, 4, 1); graph.AddEdge(3, 4, 2); ``` and call `var result = graph.Dijkstra(1);`, I expect the shortest path from node 1 to node 4 to be 7, but I'm getting 12 instead. I've checked the priority queue logic, and I think the scenario might be with how I'm managing the priority queue or updating distances, but I'm not sure where I'm going wrong. Can anyone guide to pinpoint what might be causing the unexpected behavior? Any insights on how to debug priority queues in this context would also be appreciated. Thanks! My development environment is macOS. Any help would be greatly appreciated! I'm working on a API that needs to handle this. What's the best practice here? I'm working on a REST API that needs to handle this. What's the best practice here? I'm working with C# in a Docker container on Ubuntu 20.04. Is this even possible?