📖 Scenario: You are managing tasks in a project where some tasks must be done before others. You want to find an order to do all tasks so that every task is done only after all its prerequisites are done.
🎯 Goal: Build a program that uses Depth-First Search (DFS) to find a topological order of tasks represented as a directed graph.
📋 What You'll Learn
Create a graph as an adjacency list with exact tasks and dependencies
Create a visited set to track visited tasks
Implement DFS function to explore tasks
Use DFS to find topological order
Print the final topological order as an array
💡 Why This Matters
🌍 Real World
Topological sort is used in project management, build systems, and scheduling where tasks have dependencies.
💼 Career
Understanding topological sort and DFS is important for software engineers working on compilers, task schedulers, and dependency resolution.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a constant called graph as an object with these exact keys and values: 'A': ['C'], 'B': ['C', 'D'], 'C': ['E'], 'D': ['F'], 'E': ['H', 'F'], 'F': ['G'], 'G': [], 'H': []
DSA Javascript
Hint
Use an object where each key is a task and the value is an array of tasks that depend on it.
2
Create a visited set and an empty array for order
Create a constant called visited as a new empty Set, and a constant called order as an empty array []
DSA Javascript
Hint
Use new Set() for visited and [] for order.
3
Implement DFS function and run it on all tasks
Create a function called dfs that takes a parameter task. Inside, if visited has task, return immediately. Otherwise, add task to visited. Then, for each neighbor in graph[task], call dfs(neighbor). After the loop, push task to order. Finally, use a for loop with variable task over Object.keys(graph) and call dfs(task) for each.
DSA Javascript
Hint
Use recursion to visit neighbors before pushing the current task to order.
4
Print the topological order
Print the array order reversed using console.log(order.reverse())
DSA Javascript
Hint
Reverse the order array before printing to get the correct topological order.
Practice
(1/5)
1. What is the main purpose of using DFS in Topological Sort on a directed graph?
easy
A. To count the number of connected components
B. To find the shortest path between two nodes
C. To detect cycles in an undirected graph
D. To visit nodes in a way that ensures dependencies come before dependents
Solution
Step 1: Understand DFS role in Topological Sort
DFS visits nodes deeply, ensuring all nodes reachable from a node are visited before it is processed.
Step 2: Relate DFS order to dependencies
In Topological Sort, nodes are added after visiting all their dependencies, so dependencies come before dependents.
Final Answer:
To visit nodes in a way that ensures dependencies come before dependents -> Option D
Quick Check:
DFS ensures dependency order = A [OK]
Hint: DFS post-order gives correct dependency order [OK]
Common Mistakes:
Confusing DFS with BFS for topological sorting
Thinking DFS finds shortest paths
Mixing cycle detection with topological order
2. Which of the following is the correct way to mark a node as visited in a DFS-based topological sort in JavaScript?
easy
A. visited = node;
B. visited.push(node);
C. visited[node] = true;
D. visited[node] == true;
Solution
Step 1: Understand visited marking in DFS
Visited is usually an array or object where each node's visited status is stored as a boolean.
Step 2: Correct syntax for marking visited
Assigning true to visited[node] marks that node visited; using '==' is comparison, not assignment.
Final Answer:
visited[node] = true; -> Option C
Quick Check:
Assign true to visited[node] = A [OK]
Hint: Use assignment (=), not comparison (==), to mark visited [OK]
Common Mistakes:
Using '==' instead of '=' for assignment
Using push on visited array instead of index assignment
Overwriting visited variable instead of marking node
3. What will be the output of the following code snippet performing topological sort using DFS on the graph with edges: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1?
const graph = {
5: [2, 0],
4: [0, 1],
2: [3],
3: [1],
0: [],
1: []
};
const visited = {};
const stack = [];
function dfs(node) {
visited[node] = true;
for (const neighbor of graph[node]) {
if (!visited[neighbor]) dfs(neighbor);
}
stack.push(node);
}
for (const node in graph) {
if (!visited[node]) dfs(node);
}
console.log(stack.reverse());
medium
A. [5, 4, 2, 3, 1, 0]
B. [4, 5, 0, 2, 3, 1]
C. [5, 4, 0, 2, 3, 1]
D. [4, 5, 2, 3, 1, 0]
Solution
Step 1: Perform DFS and track stack push order
DFS visits nodes deeply, pushing nodes after visiting neighbors. For node 5: visits 2, then 3, then 1, then 0; for node 4: visits 0 and 1. Stack push order is [1,3,2,0,5,4] reversed to [4,5,0,2,3,1].