Start free

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

  1. Shortest way outFind the fewest steps from S to E in a maze; # is a wall, and you move up, down,Expert
  2. Groups of friendsn people are numbered 1 to n, and m friendships are given.Expert
  3. Shortest distancesRoads join n towns (two-way, with lengths).Expert
  4. Order of coursesCourses 1 to n have prerequisites: "a b" means a must come before b.Expert
  5. Two teamsPairs of players refuse to be in the same team.Expert
  6. The extra cableCables are added one by one between computers.Expert
  7. Cheapest networkConnect all n towns with cables as cheaply as possible (a minimum spanning tree).Expert
  8. Knight's journeyOn an n by n chessboard, what is the smallest number of knight moves from one squareExpert
  9. Spreading mouldEach minute, mould (M) spreads to the fresh fruit (F) next to it (up, down, left,Expert
  10. Word ladderChange the start word into the end word one letter at a time; every word along theExpert
Start with “Shortest way out”