📖 Scenario: You are working on a project to find the shortest path from a starting point to all other points in a network that has no cycles (a Directed Acyclic Graph or DAG). This is useful in scheduling tasks where some tasks must be done before others.
🎯 Goal: Build a Java program that finds the shortest distance from a source node to all other nodes in a DAG using topological sorting.
📋 What You'll Learn
Create a graph using adjacency list representation with weights
Use a topological sort to order the nodes
Calculate shortest paths from the source node using the topological order
Print the shortest distances from the source to all nodes
💡 Why This Matters
🌍 Real World
Finding shortest paths in DAGs is useful in project scheduling, task ordering, and optimizing workflows where some tasks depend on others.
💼 Career
Understanding shortest path algorithms and topological sorting is important for software engineers working on compilers, build systems, and dependency resolution.
Progress0 / 4 steps
1
Create the graph data structure
Create an adjacency list called graph as an ArrayList of ArrayList<int[]> with 6 nodes (0 to 5). Add these edges with weights exactly: 0 -> 1 (5), 0 -> 2 (3), 1 -> 3 (6), 1 -> 2 (2), 2 -> 4 (4), 2 -> 5 (2), 2 -> 3 (7), 3 -> 4 (-1), 4 -> 5 (-2).
DSA Java
Hint
Use an ArrayList of ArrayList<int[]> to store edges and weights. Each int[] holds two values: destination node and weight.
2
Create a distance array and source node
Create an integer array called dist of size 6 and initialize all values to Integer.MAX_VALUE. Then create an integer variable called source and set it to 1. Set dist[source] to 0.
DSA Java
Hint
Use Arrays.fill(dist, Integer.MAX_VALUE) to set all distances to a large number. Set the source node distance to 0.
3
Implement topological sort and shortest path calculation
Write a method called topologicalSort that takes graph and n as parameters and returns an ArrayList<Integer> with nodes in topological order. Then, in main, call topologicalSort(graph, n) and store the result in topOrder. Use topOrder to update dist for shortest paths by relaxing edges.
DSA Java
Hint
Calculate indegrees, use a queue for nodes with zero indegree, and build the topological order. Then relax edges in that order to find shortest paths.
4
Print the shortest distances
Use a for loop with variable i from 0 to 5 to print the shortest distance from source to node i. If dist[i] is Integer.MAX_VALUE, print "INF" instead of the distance.
DSA Java
Hint
Loop through all nodes and print their distance. If distance is Integer.MAX_VALUE, print "INF".
Practice
(1/5)
1. What is the main advantage of using topological order to find the shortest path in a Directed Acyclic Graph (DAG)?
easy
A. It allows processing vertices in a linear order without revisiting nodes.
B. It guarantees the graph has cycles.
C. It sorts vertices by their weights.
D. It finds the longest path instead of the shortest.
Solution
Step 1: Understand topological order in DAG
Topological order arranges vertices so that every directed edge goes from an earlier vertex to a later one, ensuring no cycles.
Step 2: Use topological order for shortest path
Processing vertices in this order means each vertex is processed after all its predecessors, so shortest paths can be updated without revisiting nodes.
Final Answer:
It allows processing vertices in a linear order without revisiting nodes. -> Option A
Quick Check:
Topological order = linear processing without revisits [OK]
Hint: Topological order processes nodes once in correct sequence [OK]
Common Mistakes:
Thinking topological order sorts by weights
Assuming DAG has cycles
Confusing shortest path with longest path
2. Which of the following Java code snippets correctly initializes the distance array for shortest path calculation in a DAG with 5 vertices, assuming source vertex is 0?
easy
A. int[] dist = new int[5]; Arrays.fill(dist, Integer.MIN_VALUE); dist[0] = 0;
B. int[] dist = new int[5]; Arrays.fill(dist, 0); dist[0] = Integer.MAX_VALUE;
C. int[] dist = new int[5]; for(int i=0; i<5; i++) dist[i] = 0; dist[0] = 0;
D. int[] dist = new int[5]; for(int i=0; i<5; i++) dist[i] = Integer.MAX_VALUE; dist[0] = 0;
Solution
Step 1: Initialize distances to max value
Distances to all vertices except source should be set to Integer.MAX_VALUE to represent infinity.
Step 2: Set source distance to zero
Distance to source vertex 0 must be zero as it is the starting point.
Final Answer:
int[] dist = new int[5]; for(int i=0; i<5; i++) dist[i] = Integer.MAX_VALUE; dist[0] = 0; -> Option D
Quick Check:
Initialize all to max, source to zero [OK]
Hint: Set all distances max except source zero [OK]
Common Mistakes:
Setting all distances to zero
Setting source distance to max value
Using Integer.MIN_VALUE instead of max
3. Consider the following DAG with edges and weights: 0 -> 1 (2), 0 -> 2 (4), 1 -> 2 (1), 1 -> 3 (7), 2 -> 4 (3), 3 -> 4 (1) Using topological order [0,1,2,3,4], what is the shortest distance array from source 0 after processing?
No error; code correctly relaxes edges in topological order. -> Option B
Quick Check:
Relax edges with correct condition and loops [OK]
Hint: Relax edges with dist[u]+weight < dist[v] in topo order [OK]
Common Mistakes:
Confusing graph[u] with graph[e.dest]
Using wrong comparison operator
Forgetting to initialize dist array
5. You have a DAG with 6 vertices and edges: 0->1(5), 0->2(3), 1->3(6), 1->2(2), 2->4(4), 2->5(2), 2->3(7), 3->4(-1), 4->5(-2) If you run shortest path using topological order starting from vertex 0, what is the shortest distance to vertex 5?