import java.util.*;
class Graph {
static class Edge {
int to, weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
int vertices;
List<List<Edge>> adjList;
Graph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}
void addEdge(int from, int to, int weight) {
adjList.get(from).add(new Edge(to, weight));
}
void shortestPath(int start) {
int[] dist = new int[vertices];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
boolean[] visited = new boolean[vertices];
Stack<Integer> stack = new Stack<>();
// Topological sort helper
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
topologicalSort(i, visited, stack);
}
}
// Process nodes in topological order
while (!stack.isEmpty()) {
int u = stack.pop();
if (dist[u] != Integer.MAX_VALUE) {
for (Edge edge : adjList.get(u)) {
if (dist[u] + edge.weight < dist[edge.to]) {
dist[edge.to] = dist[u] + edge.weight;
}
}
}
}
// Print distances
for (int i = 0; i < vertices; i++) {
if (dist[i] == Integer.MAX_VALUE) {
System.out.println("Distance from " + start + " to " + i + " is: Infinity");
} else {
System.out.println("Distance from " + start + " to " + i + " is: " + dist[i]);
}
}
}
void topologicalSort(int v, boolean[] visited, Stack<Integer> stack) {
visited[v] = true;
for (Edge edge : adjList.get(v)) {
if (!visited[edge.to]) {
topologicalSort(edge.to, visited, stack);
}
}
stack.push(v);
}
public static void main(String[] args) {
Graph g = new Graph(5);
g.addEdge(0, 1, 2);
g.addEdge(0, 2, 4);
g.addEdge(1, 2, 1);
g.addEdge(1, 3, 7);
g.addEdge(2, 4, 3);
g.addEdge(4, 3, 1);
g.shortestPath(0);
}
}for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
topologicalSort(i, visited, stack);
}
}
Perform topological sort to order nodes so edges go forward
while (!stack.isEmpty()) {
int u = stack.pop();
if (dist[u] != Integer.MAX_VALUE) {
for (Edge edge : adjList.get(u)) {
if (dist[u] + edge.weight < dist[edge.to]) {
dist[edge.to] = dist[u] + edge.weight;
}
}
}
}
Relax edges in topological order to update shortest distances
Distance from 0 to 0 is: 0
Distance from 0 to 1 is: 2
Distance from 0 to 2 is: 3
Distance from 0 to 3 is: 7
Distance from 0 to 4 is: 6