Major Graph Algorithms Every Programmer Should Know
π Major Graph Algorithms Every Programmer Should Know π
Graphs are everywhere β from social networks and Google Maps to recommendation engines and network routing. If you know how to work with them, you can solve some of the most complex real-world problems!
In this blog, weβll explore major graph algorithms π, their logic, examples, Python code, and best use cases β plus a problem-to-algorithm cheat sheet at the end! π‘
1οΈβ£ Breadth-First Search (BFS) π
π Concept: BFS explores a graph level by level. Perfect for finding the shortest path in an unweighted graph.
π Example: Find the shortest distance between two people in a social network.
π» Python Code:
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
print(node, end=" ")
visited.add(node)
queue.extend(graph[node] - visited)
graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}
bfs(graph, 'A')
β Best Use Cases:
- Shortest path in unweighted graphs
- Social network friend recommendations
- Crawling websites
2οΈβ£ Depth-First Search (DFS) π΅οΈββοΈ
π Concept: DFS dives deep into the graph before backtracking β like exploring a maze fully before trying another path.
π Example: Check if there is a route between two cities in a road map.
π» Python Code:
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=" ")
for neighbor in graph[start] - visited:
dfs(graph, neighbor, visited)
graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}
dfs(graph, 'A')
β Best Use Cases:
- Detecting cycles in graphs
- Topological sorting (with a modified version)
- Solving puzzles like mazes or Sudoku
3οΈβ£ Dijkstraβs Algorithm π£
π Concept: Finds the shortest path in a graph with non-negative weights.
π Example: Finding the fastest driving route between cities considering road distances.
π» Python Code:
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
current_distance, current_node = heapq.heappop(pq)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
print(dijkstra(graph, 'A'))
β Best Use Cases:
- GPS navigation systems
- Network routing algorithms
- Game AI pathfinding
4οΈβ£ Bellman-Ford Algorithm β‘
π Concept: Finds shortest paths even with negative edge weights (unlike Dijkstra).
π Example: Calculating currency conversion rates when some rates might cause a loss.
π» Python Code:
def bellman_ford(graph, vertices, start):
distance = {v: float('inf') for v in vertices}
distance[start] = 0
for _ in range(len(vertices) - 1):
for u, v, w in graph:
if distance[u] + w < distance[v]:
distance[v] = distance[u] + w
return distance
edges = [
('A', 'B', 4), ('A', 'C', 5),
('B', 'C', -3), ('C', 'D', 4)
]
vertices = {'A', 'B', 'C', 'D'}
print(bellman_ford(edges, vertices, 'A'))
β Best Use Cases:
- Financial arbitrage detection
- Negative cost network routing
5οΈβ£ Floyd-Warshall Algorithm π
π Concept: Finds shortest paths between all pairs of vertices.
π Example: Finding the shortest travel time between all cities in a country.
π» Python Code:
def floyd_warshall(graph):
dist = dict(graph)
for k in graph:
for i in graph:
for j in graph:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
graph = {
'A': {'A': 0, 'B': 3, 'C': float('inf')},
'B': {'A': 2, 'B': 0, 'C': 1},
'C': {'A': float('inf'), 'B': float('inf'), 'C': 0}
}
print(floyd_warshall(graph))
β Best Use Cases:
- Precomputing shortest distances in dense graphs
- Flight connection planning
6οΈβ£ Kruskalβs Algorithm π³
π Concept: Builds a Minimum Spanning Tree (MST) by adding the smallest edges without forming cycles.
π Example: Connecting cities with the least road-building cost.
π» Python Code:
def kruskal(vertices, edges):
parent = {v: v for v in vertices}
def find(v):
while parent[v] != v:
v = parent[v]
return v
mst = []
edges.sort(key=lambda x: x[2])
for u, v, w in edges:
if find(u) != find(v):
mst.append((u, v, w))
parent[find(u)] = find(v)
return mst
vertices = ['A', 'B', 'C', 'D']
edges = [
('A', 'B', 1),
('B', 'C', 4),
('A', 'C', 3),
('C', 'D', 2)
]
print(kruskal(vertices, edges))
β Best Use Cases:
- Designing efficient road networks
- Network cabling with minimum cost
7οΈβ£ Primβs Algorithm π²
π Concept: Another MST algorithm β grows the tree from a starting vertex, adding the smallest edge each time.
π Example: Laying out electrical wiring in the cheapest way possible.
π» Python Code:
import heapq
def prim(graph, start):
visited = set([start])
edges = [
(cost, start, to)
for to, cost in graph[start].items()
]
heapq.heapify(edges)
mst = []
while edges:
cost, frm, to = heapq.heappop(edges)
if to not in visited:
visited.add(to)
mst.append((frm, to, cost))
for to_next, cost_next in graph[to].items():
if to_next not in visited:
heapq.heappush(edges, (cost_next, to, to_next))
return mst
graph = {
'A': {'B': 1, 'C': 3},
'B': {'A': 1, 'C': 4, 'D': 2},
'C': {'A': 3, 'B': 4, 'D': 5},
'D': {'B': 2, 'C': 5}
}
print(prim(graph, 'A'))
β Best Use Cases:
- Network design
- Electrical grid layout
π Problem β Algorithm Cheat Sheet π
Problem Type | Best Algorithm |
---|---|
Shortest Path (Unweighted) | BFS |
Shortest Path (Weighted, No Negative) | Dijkstra |
Shortest Path (Weighted, With Negative) | Bellman-Ford |
All-Pairs Shortest Path | Floyd-Warshall |
Minimum Spanning Tree | Kruskal / Prim |
Detect Cycle in Graph | DFS |
Connected Components | DFS / BFS |
Pathfinding in Games | A* (extension of Dijkstra) |
π― Final Thoughts
Mastering these algorithms will make you a graph wizard π§ββοΈ capable of tackling anything from network optimization to social media analytics.
Next time you face a graph problem, check the cheat sheet β itβs your quick key to choosing the right tool π.
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.