using System.Collections.Generic;
public static Dictionary<string, int> FindShortestDistances(Dictionary<string, Dictionary<string, int>> graph, string start)
var distances = graph.Keys.ToDictionary(node => node, node => int.MaxValue);
var priorityQueue = new PriorityQueue<(int, string), int>();
priorityQueue.Enqueue((0, start), 0);
while (priorityQueue.Count > 0)
(int currentDistance, string currentNode) = priorityQueue.Dequeue();
if (currentDistance > distances[currentNode])
foreach (var (neighbour, weight) in graph[currentNode])
int distance = currentDistance + weight;
if (distance < distances[neighbour])
distances[neighbour] = distance;
priorityQueue.Enqueue((distance, neighbour), distance);
public static void Main(string[] args)
var graph = new Dictionary<string, Dictionary<string, int>>
{ "Ledbury", new Dictionary<string, int> { { "Malvern", 8 }, { "Hereford", 15 }, { "Cheltenham", 22 } } },
{ "Malvern", new Dictionary<string, int> { { "Ledbury", 8 }, { "Worcester", 9 } } },
{ "Worcester", new Dictionary<string, int> { { "Malvern", 9 }, { "Hereford", 27 } } },
{ "Hereford", new Dictionary<string, int> { { "Ledbury", 15 }, { "Worcester", 27 } } }
string startNode = "Ledbury";
var shortestDistances = FindShortestDistances(graph, startNode);
Console.WriteLine($"Shortest distances from node {startNode}: {string.Join(", ", shortestDistances.Select(pair => $"{pair.Key}: {pair.Value}"))}");