Graph Algorithms: BFS, DFS, Dijkstra in Python
Graphs are one of the most versatile and powerful non-linear data structures in computer science. From modeling social network connections and GPS navigation routing to routing packets across the internet and dependency resolution in build systems, graphs represent relationships between interconnected entities.
Mastering graph traversal and shortest-path algorithms is essential for software engineers tackling technical interviews and building distributed systems. This comprehensive guide breaks down graph representations, traversal strategies (BFS and DFS), and optimal pathfinding (Dijkstra's Algorithm) with clean, production-grade Python implementations.
1. Graph Representation: Adjacency List in Python
A graph consists of vertices (nodes) connected by edges. In Python, graphs are most commonly represented using an Adjacency List, where each node maps to a list of its neighboring connected nodes.
# Adjacency list representation of an undirected graph
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
2. Breadth-First Search (BFS): Level-Order Traversal
Breadth-First Search (BFS) explores a graph level by level, visiting all neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. BFS uses a Queue (FIFO) data structure and is ideal for finding the shortest path in unweighted graphs.
from collections import deque
def bfs(graph: dict, start_node: str) -> list:
visited = set()
queue = deque([start_node])
visited.add(start_node)
traversal_order = []
while queue:
current = queue.popleft()
traversal_order.append(current)
for neighbor in graph[current]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return traversal_order
3. Depth-First Search (DFS): Exploring as Deep as Possible
Depth-First Search (DFS) explores a graph by starting at a root node and traversing as far as possible along each branch before backtracking. DFS can be implemented recursively using the call stack or iteratively using a Stack (LIFO).
# Recursive DFS Implementation
def dfs_recursive(graph: dict, current: str, visited: set = None, traversal_order: list = None) -> list:
if visited is None:
visited = set()
if traversal_order is None:
traversal_order = []
visited.add(current)
traversal_order.append(current)
for neighbor in graph[current]:
if neighbor not in visited:
dfs_recursive(graph, neighbor, visited, traversal_order)
return traversal_order
4. Dijkstra's Algorithm: Shortest Path in Weighted Graphs
While BFS finds the shortest path in unweighted graphs, it fails when edges have differing weights or costs. Dijkstra's Algorithm finds the shortest path from a source node to all other vertices in a weighted graph with non-negative edge weights, utilizing a Priority Queue (Min-Heap).
import heapq
def dijkstra(graph: dict, start: str) -> dict:
# graph format: { 'A': {'B': 4, 'C': 2}, ... }
distances = {node: float('inf') for node in graph}
distances[start] = 0
min_heap = [(0, start)] # (current_distance, node)
while min_heap:
current_dist, current_node = heapq.heappop(min_heap)
if current_dist > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(min_heap, (distance, neighbor))
return distances
Conclusion
Mastering graph traversal and pathfinding algorithms in Python—such as level-order exploration with BFS, recursive depth traversal with DFS, and optimal weight calculations with Dijkstra's Algorithm—gives developers the core foundations needed to solve complex spatial and relational programming challenges.