Graph Algorithms
Graphs are powerful data structures for modeling relationships and networks. This guide covers fundamental graph algorithms.Graph Fundamentals
Basic Concepts
Graph Definition: G(V, E)
- V: Set of vertices (nodes)
- E: Set of edges (connections)
- Directed: Edges have direction
- Undirected: Edges are bidirectional
- Weighted: Edges have weights/costs
Graph Representation
Adjacency List
Adjacency Matrix
Adjacency List vs Matrix
Adjacency List vs Matrix
| Aspect | Adjacency List | Adjacency Matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Check if edge exists | O(degree) | O(1) |
| Iterate neighbors | O(degree) | O(V) |
| Add edge | O(1) | O(1) |
| Best for | Sparse graphs | Dense graphs |
Graph Traversal
Depth-First Search (DFS)
DFS with Path Tracking
Breadth-First Search (BFS)
Topological Sort
Problem: Course Schedule II
LeetCode 210: Return course order considering prerequisites.DFS-based Topological Sort
DFS-based Topological Sort
Shortest Path Algorithms
Dijkstra’s Algorithm
Find shortest paths from single source in weighted graph with non-negative weights.Floyd-Warshall Algorithm
Find shortest paths between all pairs of nodes.Union-Find (Disjoint Set)
Efficient data structure for connectivity queries.Problem: Redundant Connection
LeetCode 684: Find edge that creates a cycle in a tree.Problem: All Paths From Source to Target
LeetCode 797: Find all paths from node 0 to node n-1 in DAG.Problem: Network Delay Time
LeetCode 743: Minimum time for signal to reach all nodes.Algorithm Comparison
| Algorithm | Use Case | Time Complexity | Space Complexity |
|---|---|---|---|
| DFS | Cycle detection, path finding | O(V + E) | O(V) |
| BFS | Shortest path (unweighted) | O(V + E) | O(V) |
| Dijkstra | Shortest path (non-negative) | O((V + E) log V) | O(V) |
| Floyd-Warshall | All pairs shortest path | O(V³) | O(V²) |
| Union-Find | Connectivity queries | O(α(n)) ≈ O(1) | O(V) |
| Topological Sort | Task scheduling | O(V + E) | O(V) |