Graph
Graph algorithms are quite common and usually fall under the following algorithms. You will usually be required to modify these algorithms to fit the problem but it's good to know the fundamentals
Time complexities
Algorithm
Time Complexity
Space Complexity
Remarks
Frequency in interviews
BFS
from collections import deque
def bfs(matrix):
# Check for an empty matrix/graph.
if not matrix:
return []
rows, cols = len(matrix), len(matrix[0])
visited = set()
directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
def traverse(i, j):
queue = deque([(i, j)])
while queue:
curr_i, curr_j = queue.popleft()
if (curr_i, curr_j) not in visited:
visited.add((curr_i, curr_j))
# Traverse neighbors.
for direction in directions:
next_i, next_j = curr_i + direction[0], curr_j + direction[1]
if 0 <= next_i < rows and 0 <= next_j < cols:
# Add in question-specific checks, where relevant.
queue.append((next_i, next_j))
for i in range(rows):
for j in range(cols):
traverse(i, j)DFS
Topological sorting
Dijkstra
Optimizations
Bellman-Ford
Optimizations
Prim’s algorithm
Fully-connected graphs
Kruskal’s algorithm
Last updated