Graphs: BFS for shortest unweighted path, DFS for cycle detection and islands — O(V+E).
Graphs
# Adjacency List (sparse graphs)
graph = {
'A': ['B','C'],
'B': ['A','D','E'],
'C': ['A','F'],
'D': ['B'],
'E': ['B','F'],
'F': ['C','E']
}
# BFS -- shortest path (unweighted), O(V+E)
from collections import deque
def bfs(graph, start, goal):
queue = deque([[start]])
visited = {start}
while queue:
path = queue.popleft()
node = path[-1]
if node == goal: return path
for nb in graph[node]:
if nb not in visited:
visited.add(nb)
queue.append(path + [nb])
return None
# DFS -- cycle detection, topological sort, O(V+E)
def dfs(graph, node, visited=None):
if visited is None: visited = set()
visited.add(node)
for nb in graph[node]:
if nb not in visited:
dfs(graph, nb, visited)
return visited
# Number of islands (grid graph)
def num_islands(grid):
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1':
dfs_island(grid, r, c)
count += 1
return count