using
System;
using
System.Collections.Generic;
public
class
ShortestPath
{
static
readonly
int
INF =
int
.MaxValue;
class
AdjListNode
{
public
int
v;
public
int
weight;
public
AdjListNode(
int
_v,
int
_w) { v = _v; weight = _w; }
public
int
getV() {
return
v; }
public
int
getWeight() {
return
weight; }
}
class
Graph
{
public
int
V;
public
List<AdjListNode>[]adj;
public
Graph(
int
v)
{
V = v;
adj =
new
List<AdjListNode>[V];
for
(
int
i = 0; i < v; ++i)
adj[i] =
new
List<AdjListNode>();
}
public
void
addEdge(
int
u,
int
v,
int
weight)
{
AdjListNode node =
new
AdjListNode(v,weight);
adj[u].Add(node);
}
public
void
topologicalSortUtil(
int
v, Boolean []visited,
Stack<
int
> stack)
{
visited[v] =
true
;
foreach
(AdjListNode it
in
adj[v])
{
AdjListNode node = it;
if
(!visited[node.getV()])
topologicalSortUtil(node.getV(), visited, stack);
}
stack.Push(v);
}
public
void
shortestPath(
int
s)
{
Stack<
int
> stack =
new
Stack<
int
>();
int
[]dist =
new
int
[V];
Boolean []visited =
new
Boolean[V];
for
(
int
i = 0; i < V; i++)
visited[i] =
false
;
for
(
int
i = 0; i < V; i++)
if
(visited[i] ==
false
)
topologicalSortUtil(i, visited, stack);
for
(
int
i = 0; i < V; i++)
dist[i] = INF;
dist[s] = 0;
while
(stack.Count != 0)
{
int
u = (
int
)stack.Pop();
if
(dist[u] != INF)
{
foreach
(AdjListNode it
in
adj[u])
{
AdjListNode i= it;
if
(dist[i.getV()] > dist[u] + i.getWeight())
dist[i.getV()] = dist[u] + i.getWeight();
}
}
}
for
(
int
i = 0; i < V; i++)
{
if
(dist[i] == INF)
Console.Write(
"INF "
);
else
Console.Write( dist[i] +
" "
);
}
}
}
Graph newGraph(
int
number)
{
return
new
Graph(number);
}
public
static
void
Main(String []args)
{
ShortestPath t =
new
ShortestPath();
Graph g = t.newGraph(6);
g.addEdge(0, 1, 5);
g.addEdge(0, 2, 3);
g.addEdge(1, 3, 6);
g.addEdge(1, 2, 2);
g.addEdge(2, 4, 4);
g.addEdge(2, 5, 2);
g.addEdge(2, 3, 7);
g.addEdge(3, 4, -1);
g.addEdge(4, 5, -2);
int
s = 1;
Console.WriteLine(
"Following are shortest distances "
+
"from source "
+ s );
g.shortestPath(s);
}
}