Code

Mapping the Islands

A graph is a set of nodes joined by edges, islands and bridges, friends and friendships, web pages and links. The handiest representation is an adjacency list: a dict from each node to a list of its neighbors.

islands = {
    "Port": ["Mill", "Reef"],
    "Mill": ["Port", "Tower"],
    "Reef": ["Port", "Tower"],
    "Tower": ["Mill", "Reef"],
}

Breadth-first search (BFS)

You met BFS on a grid in the Labyrinth. It works on any graph. BFS explores in rings: all neighbors first, then their neighbors. It uses a queue, and a seen set so we never visit twice (graphs can have loops!).

from collections import deque

def bfs_order(graph, start):
    seen, order = {start}, []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph[node]:
            if nxt not in seen:
                seen.add(nxt)
                queue.append(nxt)
    return order

Because BFS goes ring by ring, the first time it reaches a node is along the path with the fewest edges.

Depth-first search (DFS)

DFS dives as deep as it can before backing up, like exploring a cave. It uses a stack, or simply recursion.

Assignment

  1. dfs_order(graph, start) returns nodes in recursive DFS order: visit a node, then each unvisited neighbor in listed order.
  2. hops(graph, start, goal) returns the fewest bridges from start to goal (0 if they're the same), or -1 if unreachable. Use BFS and store each node's distance in a dict.