
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
dfs_order(graph, start)returns nodes in recursive DFS order: visit a node, then each unvisited neighbor in listed order.hops(graph, start, goal)returns the fewest bridges fromstarttogoal(0 if they're the same), or-1if unreachable. Use BFS and store each node's distance in a dict.
dfs_order(graph, start)returns nodes in recursive DFS order: visit a node, then each unvisited neighbor in listed order.hops(graph, start, goal)returns the fewest bridges fromstarttogoal(0 if they're the same), or-1if unreachable. Use BFS and store each node's distance in a dict.
main.py Python sleeping
Press Run to try your code, then Check to test it.