Skip to content
CodeItRaw
Graphs

Lesson 1/4

A graph is made of nodes and the edges that join them: cities and roads, pages and links, the cells of a maze and the ways between them. Unlike a tree it has no root and no direction: a node can be reached by more than one way, and the ways can form loops.

graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
stack = ["a"]
seen = {"a"}
while stack:
node = stack.pop()
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
The usual way to hold a graph is an adjacency list: next to each node, its neighbours. To walk it you keep the nodes still to visit on a stack; when a node comes off, its unseen neighbours go on. This is depth-first search (DFS): it follows one way to its end and then comes back.

A grid is a graph too, only its adjacency list is not written down: a cell's neighbours are the cells above, below, left and right of it. The bot that follows a wall through a maze is walking a graph.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Data Maze

    Infiltration

  2. 02

    Walking with a Stack

    Code reading · Predict the Output

If you would rather not wait for the order, every problem is open without locks: Problem list