A level · 10 exercises
Python graphs
A graph is places (nodes) joined by edges. Keep it as a dictionary of neighbours: graph[a] is the list of nodes next to a.
Breadth-first search, with a queue, finds the shortest path when every step costs the same; Dijkstra's algorithm, with a heap, when steps cost different amounts.
from collections import deque
graph = {1: [2, 3], 2: [4], 3: [4], 4: []}
dist = {1: 0}
queue = deque([1])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in dist:
dist[nxt] = dist[node] + 1
queue.append(nxt)
print(dist[4])Watch for: Mark a node as seen when you add it to the queue, not when you take it out, or it is added many times.
Exercises
- Shortest way outFind the fewest steps from S to E in a maze; # is a wall, and you move up, down,Expert
- Groups of friendsn people are numbered 1 to n, and m friendships are given.Expert
- Shortest distancesRoads join n towns (two-way, with lengths).Expert
- Order of coursesCourses 1 to n have prerequisites: "a b" means a must come before b.Expert
- Two teamsPairs of players refuse to be in the same team.Expert
- The extra cableCables are added one by one between computers.Expert
- Cheapest networkConnect all n towns with cables as cheaply as possible (a minimum spanning tree).Expert
- Knight's journeyOn an n by n chessboard, what is the smallest number of knight moves from one squareExpert
- Spreading mouldEach minute, mould (M) spreads to the fresh fruit (F) next to it (up, down, left,Expert
- Word ladderChange the start word into the end word one letter at a time; every word along theExpert