Graph Algorithms Cheat Sheet
Core graph traversal and shortest-path algorithms — BFS, DFS, Dijkstra — with adjacency list representations and complexity comparisons.
2 PagesIntermediateApr 10, 2026
Graph Representation
Adjacency list representation for weighted and unweighted graphs.
python
from collections import defaultdictgraph = defaultdict(list)graph[0].append(1) # edge 0 -> 1graph[1].append(2)graph[0].append(2)# Weighted graph: store (neighbor, weight) tuplesweighted = defaultdict(list)weighted[0].append((1, 4)) # edge 0->1 with weight 4weighted[1].append((2, 2))
BFS & DFS Traversal
Breadth-first and depth-first traversal using a queue and a stack.
python
from collections import dequedef bfs(graph, start): visited, queue, order = {start}, deque([start]), [] while queue: node = queue.popleft() order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return orderdef dfs(graph, start): visited, stack, order = set(), [start], [] while stack: node = stack.pop() if node not in visited: visited.add(node) order.append(node) stack.extend(graph[node]) return order
Dijkstra's Shortest Path
Single-source shortest paths on a weighted graph using a min-heap.
python
import heapqdef dijkstra(graph, start): dist = {start: 0} pq = [(0, start)] while pq: d, node = heapq.heappop(pq) if d > dist.get(node, float('inf')): continue for neighbor, weight in graph[node]: nd = d + weight if nd < dist.get(neighbor, float('inf')): dist[neighbor] = nd heapq.heappush(pq, (nd, neighbor)) return dist
Algorithm Complexity
Time complexity of common graph algorithms, V = vertices, E = edges.
- BFS / DFS- O(V + E) time, O(V) space; BFS finds shortest path in unweighted graphs
- Dijkstra (binary heap)- O((V + E) log V); requires non-negative edge weights
- Bellman-Ford- O(V * E); slower than Dijkstra but handles negative edge weights and detects negative cycles
- Floyd-Warshall- O(V^3); computes shortest paths between all pairs of vertices
- Kruskal's MST- O(E log E); builds a minimum spanning tree using union-find to avoid cycles
- Prim's MST- O(E log V) with a binary heap; grows the MST one vertex at a time
- Topological Sort- O(V + E); only valid on a directed acyclic graph (DAG)
- A* Search- O(E) with an admissible heuristic; best for single-target pathfinding
Pro Tip
For sparse graphs (E much less than V^2), always prefer an adjacency list over an adjacency matrix — matrices cost O(V^2) memory regardless of edge count and only pay off when the graph is dense.
Was this cheat sheet helpful?
Explore Topics
#GraphAlgorithms#GraphAlgorithmsCheatSheet#Programming#Intermediate#GraphRepresentation#BFSDFSTraversal#DijkstraSShortestPath#AlgorithmComplexity#DataStructures#Algorithms#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance