BFS, DFS, Topological Sort, Strongly Connected Components, Dijkstra's Algorithm
Draw a simple graph and convert it between both representations. This is a common exam question!
BFS Order from A: A ā B ā C ā D ā E ā F ā G ā H
Queue progression: [A] ā [B,C] ā [C,D,E] ā [D,E,F,G] ā [E,F,G] ā [F,G,H] ā [G,H] ā [H] ā []
Try this yourself: Given the graph above, what would be the BFS traversal starting from node C?
Answer: C ā B ā A ā F ā G ā D ā E ā H
Explanation:
Queue: [C] ā [B,F,G] ā [F,G,A] ā [G,A,D,E] ā [A,D,E] ā [D,E] ā [E,H] ā [H] ā []
Q1: What data structure does BFS use?
Q2: In an unweighted graph, BFS finds:
Q3: What is the space complexity of BFS?
Try explaining these in your own words (cover the answer first!):
Remember: DFS on an undirected graph only has tree and back edges. Forward and cross edges only appear in directed graphs!
Dijkstra's FAILS with negative weights! Use Bellman-Ford for negative weights (though this might not be on your exam based on syllabus).
| Algorithm | Time Complexity | Space | Key Use |
|---|---|---|---|
| BFS | O(V + E) | O(V) | Shortest path (unweighted) |
| DFS | O(V + E) | O(V) | Cycle detection, topological sort |
| Topological Sort | O(V + E) | O(V) | Task scheduling (DAGs only) |
| SCC (Kosaraju) | O(V + E) | O(V) | Find strongly connected components |
| Dijkstra | O((V+E) log V) | O(V) | Shortest path (non-negative weights) |
Based on ps1: Click vertices in the order they would be visited. Test your understanding!
Instructions: Click vertices in the order BFS would visit them starting from node A. When multiple nodes can be enqueued, choose alphabetically.
A ā B ā F ā H ā D ā E ā C ā G
Remember: When multiple nodes are at the same level, enqueue alphabetically!
Instructions: Click vertices in the order DFS would visit them starting from node A. When multiple nodes can be explored, choose alphabetically.
A ā B ā D ā G ā F ā E ā H ā C
Stack trace: A ā [B,F,H] ā B ā [D] ā D ā [G] ā G ā backtrack ā F ā [E] ā E ā backtrack ā H ā [C] ā C ā done
DFS explores as deep as possible before backtracking!
BFS uses a Queue (FIFO - processes closest nodes first), while DFS uses a Stack/Recursion (LIFO - goes as deep as possible first).
Both visit all reachable nodes, but in very different orders!