using System;
using System.Collections.Generic;
// This class represents a directed graph using
// adjacency list representation
class Graph {
private int V;
private List<KeyValuePair<int, int> >[] adj;
public Graph(int V)
{
this.V = V;
adj = new List<KeyValuePair<int, int> >[ V ];
for (int i = 0; i < V; i++) {
adj[i] = new List<KeyValuePair<int, int> >();
}
}
// function to add an reverse edge to graph
// prints shortest distance from all
// vertex to the given destination vertex
void addEdgeRev(int u, int v, int w)
{
adj[v].Add(new KeyValuePair<int, int>(u, w));
}
// prints shortest distance from all
// vertex to the given destination vertex
public void shortestPath(int dest)
{
SortedSet<KeyValuePair<int, int> > pq
= new SortedSet<KeyValuePair<int, int> >(
Comparer<KeyValuePair<int, int> >.Create(
(a, b) = > a.Key.CompareTo(b.Key)));
int[] dist = new int[V];
Array.Fill(dist, int.MaxValue);
pq.Add(new KeyValuePair<int, int>(0, dest));
dist[dest] = 0;
// The first vertex in pair is the minimum distance
// vertex, extract it from priority queue.
// vertex label is stored in second of pair (it
// has to be done this way to keep the vertices
// sorted distance (distance must be first item
// in pair)
while (pq.Count > 0) {
int u = pq.Min.Value;
pq.Remove(pq.Min);
foreach(KeyValuePair<int, int> pair in adj[u])
{
int v = pair.Key;
int weight = pair.Value;
if (dist[v] > dist[u] + weight) {
dist[v] = dist[u] + weight;
pq.Add(new KeyValuePair<int, int>(
dist[v], v));
}
}
}
Console.WriteLine(
"Destination Vertex Distance from all vertex");
for (int i = 0; i < V; i++) {
Console.WriteLine(i + " \t\t " + dist[i]);
}
}
// Driver code
public static void Main(string[] args)
{
Graph g = new Graph(5);
g.addEdgeRev(0, 2, 1);
g.addEdgeRev(0, 4, 5);
g.addEdgeRev(1, 4, 1);
g.addEdgeRev(2, 0, 10);
g.addEdgeRev(2, 3, 5);
g.addEdgeRev(3, 1, 1);
g.addEdgeRev(4, 0, 5);
g.addEdgeRev(4, 2, 100);
g.addEdgeRev(4, 3, 5);
g.shortestPath(0);
}
}