using System;
using System.Collections.Generic;
namespace DijkstrasAlgorithm
{
class Program
{
static void Main(string[] args)
{
// Create graph
Graph graph = new Graph();
graph.AddNode("A", new Dictionary<string, int> { { "B", 4 }, { "C", 2 } });
graph.AddNode("B", new Dictionary<string, int> { { "A", 4 }, { "C", 1 }, { "D", 5 } });
graph.AddNode("C", new Dictionary<string, int> { { "A", 2 }, { "B", 1 }, { "D", 8 }, { "E", 10 } });
graph.AddNode("D", new Dictionary<string, int> { { "B", 5 }, { "C", 8 }, { "E", 2 }, { "F", 6 } });
graph.AddNode("E", new Dictionary<string, int> { { "C", 10 }, { "D", 2 }, { "F", 3 } });
graph.AddNode("F", new Dictionary<string, int> { { "D", 6 }, { "E", 3 } });
// Find shortest paths
Dictionary<string, int> shortestPaths = graph.FindShortestPaths("A");
// Print results
Console.WriteLine("Shortest paths from A:");
foreach (KeyValuePair<string, int> pair in shortestPaths)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
Console.ReadKey();
}
}
class Graph
{
private Dictionary<string, Dictionary<string, int>> nodes = new Dictionary<string, Dictionary<string, int>>();
public void AddNode(string name, Dictionary<string, int> edges)
{
nodes[name] = edges;
}
public Dictionary<string, int> FindShortestPaths(string startNode)
{
Dictionary<string, int> distances = new Dictionary<string, int>();
Dictionary<string, string> previous = new Dictionary<string, string>();
List<string> nodesList = new List<string>();
foreach (KeyValuePair<string, Dictionary<string, int>> pair in nodes)
{
string nodeName = pair.Key;
if (nodeName == startNode)
{
distances[nodeName] = 0;
}
else
{
distances[nodeName] = int.MaxValue;
}
previous[nodeName] = null;
nodesList.Add(nodeName);
}
while (nodesList.Count > 0)
{
nodesList.Sort((x, y) => distances[x] - distances[y]);
string smallestNode = nodesList[0];
nodesList.RemoveAt(0);
if (distances[smallestNode] == int.MaxValue)
{
break;
}
foreach (KeyValuePair<string, int> pair in nodes[smallestNode])
{
string neighbor = pair.Key;
int dist = pair.Value;
int alt = distances[smallestNode] + dist;
if (alt < distances[neighbor])
{
distances[neighbor] = alt;
previous[neighbor] = smallestNode;
}
}
}
return distances;
}
}
}