This page is due for review. Re-read the key points and answer the self-check questions before recording your video.
Algorithms · Hub
Graphs
Eleven pages on graphs: how to store them, how to walk them (BFS, DFS), how to find shortest paths (Dijkstra, Bellman-Ford, Floyd-Warshall), how to connect everything cheaply (Kruskal, Prim), and how to order and check them (topological sort, cycle detection, Union-Find).
Why it matters: roads, networks, dependencies and social links are all graphs. Knowing which algorithm fits which question, and its precondition, is most of the work.
5 random questions mixed from all eleven graph pages.
Mixed review
Answer each one out loud before opening the sample answer.
Quick comparison
Algorithm
Solves
Time
Precondition
BFS
Traversal, shortest path in edges
$O(V + E)$
Unweighted for shortest paths
DFS
Traversal, components, order
$O(V + E)$
None
Dijkstra
Single-source shortest paths
$O((V + E) \log V)$
Non-negative weights
Bellman-Ford
Single-source shortest paths
$O(VE)$
No reachable negative cycle
Floyd-Warshall
All-pairs shortest paths
$O(V^3)$
No negative cycle
Kruskal
Minimum spanning tree
$O(E \log E)$
Undirected, connected
Prim
Minimum spanning tree
$O(V^2)$ or $O(E \log V)$
Undirected, connected
Topological sort
Dependency order
$O(V + E)$
Directed acyclic graph
Cycle detection
Is there a cycle?
$O(V + E)$
None
Union-Find
Same group? Merge groups
$O(\alpha(n))$ per operation
Merges only
The eleven graph pages
Graph representations
Adjacency matrix versus adjacency lists.
O(V²) vs O(V + E) memory · O(1) vs O(deg) edge check
flowchart TD
A{"What do you need?"} -->|"visit everything"| T{"Need shortest paths in edges?"}
T -->|yes| BFS["BFS"]
T -->|no| DFS["DFS"]
A -->|"shortest weighted paths"| S{"From one source or all pairs?"}
S -->|"all pairs"| FW["Floyd-Warshall"]
S -->|"one source"| N{"Any negative edge?"}
N -->|no| DJ["Dijkstra"]
N -->|yes| BF["Bellman-Ford"]
A -->|"cheapest network connecting all"| M{"Dense graph?"}
M -->|yes| PR["Prim"]
M -->|no| KR["Kruskal"]
A -->|"order tasks with dependencies"| TS["Topological sort"]
A -->|"is there a loop?"| CD["Cycle detection"]
A -->|"which items are connected?"| UF["Union-Find"]
Key points
Adjacency lists make traversals $O(V + E)$ because they store only real edges.
BFS gives shortest unweighted paths because it reaches vertices layer by layer.
Dijkstra needs non-negative weights because it declares distances final as soon as they are the smallest.
Bellman-Ford and Floyd-Warshall allow negative edges because they never finalise a distance early.
Kruskal and Prim are both greedy because the cheapest edge across any cut is always safe for a minimum spanning tree.