Graphs

Graphs arrive as adjacency dictionaries, edge lists or grids. Convert to whichever form you can search, then it is BFS or DFS with a visited set.

The lesson is Graphs.

Count each node's connections

Write degrees(edges) that, for a two-way graph given as a list of (a, b) pairs, returns a dictionary from each node to how many edges touch it.

degrees([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])  ->  {"A": 2, "B": 2, "C": 3, "D": 1}
degrees([])  ->  {}

The point is to practise reading an edge list with a Counter.

def degrees(edges):
    ...

Does the network contain a loop?

graph is an adjacency dictionary for a two-way graph with every node as a key and no edge listed twice. Write has_cycle(graph) that returns whether any cycle exists.

has_cycle({1: [2], 2: [1, 3], 3: [2]})           ->  False     (a line)
has_cycle({1: [2, 3], 2: [1, 3], 3: [1, 2]})     ->  True      (a triangle)
has_cycle({1: [2], 2: [1], 3: [4], 4: [3]})      ->  False

The point is to practise DFS that remembers where it came from: in an undirected graph, seeing a visited neighbour that is not your parent means a cycle.

def has_cycle(graph):
    ...

Can the nodes be split into two teams?

Write is_bipartite(graph) that returns whether the nodes of the two-way graph can be coloured with two colours so that no edge joins two nodes of the same colour. Every node is a key.

is_bipartite({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})  ->  True     (a square)
is_bipartite({0: [1, 2], 1: [0, 2], 2: [0, 1]})             ->  False    (a triangle)
is_bipartite({})  ->  True

The point is to practise BFS that assigns alternating labels and checks for conflicts.

def is_bipartite(graph):
    ...

The shortest route itself

Write shortest_path(graph, start, goal) that returns the list of nodes on a shortest route from start to goal in a two-way graph, including both ends, or [] if there is none. When several shortest routes exist, return the one BFS finds when neighbours are explored in the order they are listed.

graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C", "E"], "E": ["D"]}
shortest_path(graph, "A", "E")  ->  ["A", "B", "D", "E"]
shortest_path(graph, "A", "A")  ->  ["A"]
shortest_path({"A": [], "B": []}, "A", "B")  ->  []

The point is to practise recording predecessors during BFS and walking them back.

def shortest_path(graph, start, goal):
    ...

Order the tasks

prereqs is a dictionary from each task to the list of tasks that must be done before it. Every task is a key, and there are no circular requirements. Write task_order(prereqs) that returns a list of all tasks in an order where every task comes after its prerequisites. Any valid order passes.

task_order({"wake": [], "dress": ["wake"], "eat": ["wake"], "leave": ["dress", "eat"]})
    ->  ["wake", "dress", "eat", "leave"]    (or ["wake", "eat", "dress", "leave"])

The point is to practise topological sorting: repeatedly take a task with no remaining prerequisites.

def task_order(prereqs):
    ...

Can every course be taken?

prereqs is a dictionary from each course to the courses required before it; every course is a key. Write can_finish(prereqs) that returns whether it is possible to take them all, which fails only when requirements go round in a circle.

can_finish({"a": [], "b": ["a"]})       ->  True
can_finish({"a": ["b"], "b": ["a"]})    ->  False
can_finish({"a": ["a"]})                ->  False

The point is to practise cycle detection in a directed graph.

def can_finish(prereqs):
    ...

Flood fill

image is a list of lists of whole numbers (colours). Write flood_fill(image, r, c, colour) that changes the cell at (r, c) and every cell connected to it (up, down, left, right) through cells of the same original colour to the new colour, in place, and returns image.

flood_fill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2)  ->  [[2, 2, 2], [2, 2, 0], [2, 0, 1]]
flood_fill([[0, 0]], 0, 0, 0)                          ->  [[0, 0]]   (same colour: nothing changes)

The point is to practise a search on a grid that stops at a colour boundary. Watch the case where the new colour equals the old one, which loops forever if handled naively.

def flood_fill(image, r, c, colour):
    ...

Steps through a maze

maze is a list of strings using S for the start, E for the exit, # for walls and . for open floor. Moves go up, down, left or right. Write maze_steps(maze) that returns the fewest moves from S to E, or -1 if the exit cannot be reached.

maze_steps(["S.#", ".##", "..E"])  ->  4
maze_steps(["S#E"])                ->  -1

The point is to practise BFS on a grid with a distance map.

def maze_steps(maze):
    ...

Largest island

grid is a list of strings of 1 (land) and 0 (water). Write max_island(grid) that returns the number of cells in the largest island (cells connected up, down, left or right), or 0 if there is no land.

max_island(["110", "010", "001"])  ->  3
max_island(["000"])                ->  0

The point is to practise measuring each component rather than just counting them.

def max_island(grid):
    ...

How long until everything rots?

grid is a list of lists where 0 is empty, 1 is a fresh orange and 2 is a rotten one. Every minute, each rotten orange rots the fresh oranges directly up, down, left and right of it. Write minutes_to_rot(grid) that returns how many minutes until no fresh orange remains, or -1 if some fresh orange can never be reached.

minutes_to_rot([[2, 1, 1], [1, 1, 0], [0, 1, 1]])  ->  4
minutes_to_rot([[2, 1, 1], [0, 1, 1], [1, 0, 1]])  ->  -1
minutes_to_rot([[0, 2]])                           ->  0

The point is to practise BFS from many sources at once: every rotten orange starts in the queue with time 0.

def minutes_to_rot(grid):
    ...

Next: Heaps.