Graph Algorithms
Implement graph data structures and algorithms — BFS, DFS, shortest paths, minimum spanning trees, and topological sorting.
50 min•By Priygop Team•Last updated: Feb 2026
Graph Representation & Traversal
- Adjacency Matrix: 2D array — graph[i][j] = 1 if edge exists. O(V²) space. O(1) edge check. Best for dense graphs or when V is small
- Adjacency List: Array of linked lists — each vertex stores list of its neighbors. O(V+E) space. Better for sparse graphs (most real-world graphs)
- BFS (Breadth-First Search): Use queue — visit all neighbors before going deeper. Finds shortest path in unweighted graphs. O(V+E) time. Level-order exploration
- DFS (Depth-First Search): Use stack or recursion — go as deep as possible before backtracking. Detects cycles, topological sort, connected components. O(V+E)
- Dijkstra's Algorithm: Shortest path from source to all vertices in weighted graph (non-negative weights). Uses priority queue (min-heap). O((V+E) log V)
- Bellman-Ford: Shortest path with negative weights. Relax all edges V-1 times. Detects negative cycles on Vth iteration. O(V×E). Slower but more versatile than Dijkstra
Try It Yourself: Bubble Sort
Try It Yourself: Bubble SortC
C Editor
✓ ValidTab = 2 spaces
C|34 lines|681 chars|✓ Valid syntax
UTF-8