Dijkstra's Algorithm, because weight matters!


Dijkstra's algorithm is one of the most popular algorithms for finding the shortest path in a graph with non-negative weights.

public static void DijkstrasAlgorithm(Dictionary<string, Dictionary<string, int>> graph, string start, string end)
{
var shortestDistances = new Dictionary<string, int>();
var predecessor = new Dictionary<string, string>();
var nodes = new List<string>();

foreach (var node in graph)
{
if (node.Key == start)
{
shortestDistances[node.Key] = 0;
}
else
{
shortestDistances[node.Key] = int.MaxValue;
}

nodes.Add(node.Key);
}

while (nodes.Count != 0)
{
nodes.Sort((node1, node2) => shortestDistances[node1].CompareTo(shortestDistances[node2]));

var smallest = nodes[0];
nodes.RemoveAt(0);

if (smallest == end)
{
var path = new List<string>();
while (predecessor.ContainsKey(smallest))
{
path.Add(smallest);
smallest = predecessor[smallest];
}

path.Add(start);
path.Reverse();

Console.WriteLine("Shortest path is " + string.Join(" -> ", path));
return;
}

if (shortestDistances[smallest] == int.MaxValue)
{
break;
}

foreach (var neighbor in graph[smallest])
{
var alt = shortestDistances[smallest] + neighbor.Value;
if (alt < shortestDistances[neighbor.Key])
{
shortestDistances[neighbor.Key] = alt;
predecessor[neighbor.Key] = smallest;
}
}
}

Console.WriteLine("Path does not exist!");
}

 


No files yet, migration hasn't completed yet!