Graphs

Graphs — BFS & DFS

Nodes + edges. BFS = shortest path (unweighted). DFS = connected components, cycle detection, topological sort.

BFS vs DFS on Same Graph
Visit order: []
Press BFS or DFS to explore from node A.

BFS vs DFS — When to Use Which

Use BFS when...Use DFS when...
Shortest path (unweighted)Connected components
Level-order traversalCycle detection
Minimum steps to reach targetTopological sort
Closest neighborPath exists (yes/no)
Always mark visited BEFORE enqueuing (BFS)
Marking visited when you process (dequeue) means the same node can be added to the queue multiple times. Mark WHEN you add to queue.
Topological Sort (Kahn's BFS)

Find valid ordering where every prerequisite comes before the course. Start from nodes with in-degree=0.

Press Run to see Kahn's topological sort.

Cycle Detection

If Kahn's result has fewer nodes than total → there's a cycle!
A cycle means some nodes always have in-degree > 0 and never get processed. This is exactly how "Course Schedule" works: if result length < numCourses → cycle.

BFS + DFS Templates

from collections import deque, defaultdict

# Build adjacency list
graph = defaultdict(list)
for u, v in edges:
    graph[u].append(v)
    graph[v].append(u)  # undirected

# BFS — shortest path
def bfs(graph, start, target):
    q, visited, dist = deque([(start, 0)]), {start}, {}
    while q:
        node, d = q.popleft()
        if node == target: return d
        for nei in graph[node]:
            if nei not in visited:
                visited.add(nei); q.append((nei, d+1))

# DFS — iterative with stack
def dfs(graph, start):
    stack, visited = [start], {start}
    while stack:
        node = stack.pop()
        for nei in graph[node]:
            if nei not in visited:
                visited.add(nei); stack.append(nei)

Kahn's Topological Sort

def topo_sort(numNodes, edges):
    graph = defaultdict(list)
    in_degree = [0] * numNodes
    for u, v in edges:
        graph[u].append(v); in_degree[v] += 1

    q = deque(i for i in range(numNodes) if in_degree[i] == 0)
    result = []
    while q:
        node = q.popleft(); result.append(node)
        for nei in graph[node]:
            in_degree[nei] -= 1
            if in_degree[nei] == 0: q.append(nei)
    # if len(result) < numNodes → cycle!
    return result if len(result) == numNodes else []

LeetCode Problems

  • MediumNumber of IslandsDFS/BFS on grid
  • MediumClone GraphDFS + hashmap
  • MediumCourse ScheduleKahn's + cycle detection
  • MediumRotting OrangesMulti-source BFS
  • MediumPacific Atlantic Water FlowReverse BFS from coasts
  • HardWord LadderBFS on word graph
  • HardAlien DictionaryKahn's topological sort