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
BFS
DFS
Space accounting for stack frames used in recursion
Topological Sorting
for storing the edges and frontier
Note that when iterating over every node, we only decrease the edges at most times
Dijkstra
for priority queue
Bellman-Ford
For vertices, we iterate through all edges and compute the SSP
Primās Algorithm
or
Time complexity achieved if using Fibonacci heap AND iterating over the entire priority queue
Kruskalās Algorithm
Frequency in interviews
Common: BFS, DFS
Uncommon: Topological sort, Dijkstra
Almost never: Bellman-Ford, Floyd Warshall, Primās, Kruskalās
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
Used for job scheduling a sequence of jobs or tasks that have dependencies on other jobs/tasks
Jobs represent vertices and edges from X to Y (directed) if X depends on Y
Dijkstra
Optimizations
If target node known, once we process target node (i.e. pop is target node), we can early return
Bellman-Ford
Loop for v - 1 times and for each loop, relax all edges
To detect negative weight edges, check if the cost of the same node decreases twice
Optimizations
Track if any costs decreased, if none did, then we can early terminate since that means we found the lowest possible cost for all edges
Primās algorithm
Finds the Minimum Spanning Tree of a graph and is easier to implement than Kruskalās algorithm
For this specific implementation, the time complexity is
Fully-connected graphs
For fully connected graphs, instead of using a heap, use a min_d array, tracking the minimum weight to reach each point in the graph.
Kruskalās algorithm
Use Union-Find Disjoint Set (UFDS) to determine which edges are redundant and use a min heap to store the weights of the edges. Redundant edges are those whose points already exist in the same set (meaning that there exists another path between these two points in the MST so far).
This implementation has a time complexity of because weāre not sorting the entire graph at once. If we sorted, the time complexity would be similar but dominates the term so we take that instead
Last updated