Walk adjacency lists and implicit graphs (lock codes, word ladders) breadth first and depth first, count components and clone a graph.
A parcel-delivery app moves parcels between eight hubs. Trucks run both ways between some pairs of hubs. Your team lead explains the problem.
Your team lead says: A parcel is stuck at hub 0. I need two answers. Which hubs can it still reach, and what is the fewest number of transfers to hub 5?
The truck links are written as pairs of hub numbers: [[0, 2], [0, 4], [1, 3], [1, 5], [2, 5], [3, 4], [6, 7]]. A pair such as [0, 2] means a truck runs between hub 0 and hub 2, in both directions.
This is a graph. Each hub is a node, and each link is an edge. It is not a grid: there is no up, right, down or left. So how does a search find the neighbours of a hub?
A list of links is easy to write, but slow to search: finding the neighbours of one hub means reading every link. So you build an adjacency list once. It gives each hub a list of its neighbours.
| Hub | Its neighbours |
|---|---|
| 0 | 2, 4 |
| 1 | 3, 5 |
| 2 | 0, 5 |
| 3 | 1, 4 |
| 4 | 0, 3 |
| 5 | 1, 2 |
| 6 | 7 |
| 7 | 6 |
A two-way link goes in both lists. The link [0, 2] puts 2 in the list of hub 0, and 0 in the list of hub 2. Building all the lists costs one step per link, and after that a hub finds its neighbours at once.
A list of links becomes an adjacency list: every two-way link adds one entry at each of its two ends.
Exercise · Put it in order: Build the adjacency lists. Arrange the lines into a function that turns two-way truck links into adjacency lists: entry h is the list of hubs linked to hub h, in the order the links are given.
def build_graph(n, links):
graph = [[] for _ in range(n)]
for a, b in links:
graph[a].append(b)
graph[b].append(a)
return graph
graph[b] = [a]On a grid, a rule finds the neighbours of a cell. In a graph, the list does. That is the only thing that changes for BFS and DFS. The rest of each search stays exactly as you learned it.
You tell a rumour to everyone you know. In the next round, each of them tells everyone they know. After one round, everybody one link away has heard it. After two rounds, everybody two links away has heard it.
Breadth-first search (BFS) explores a graph the same way, in rounds. The round in which a hub is reached is its number of links from the start, so the first round to reach hub 5 gives the fewest transfers.
BFS is a rumour: each round, everyone who just heard it tells everyone they know.
You read an article and follow one of its footnotes. That page has footnotes too, so you follow the first one, and the next, until you reach a page with nothing new. Then you go back one page and try its next footnote.
Depth-first search (DFS) explores a graph the same way. It follows one route as far as it can, and it backs up only when it is stuck. It reaches every connected hub, but the first route it finds may be a long one.
DFS is a chain of footnotes: follow one as deep as it goes, then go back and try the next.
Predict what happens
Q The adjacency lists are built from the links above. Hub 3 appears in the links [1, 3] and [3, 4]. How many hubs are in hub 3's list?
Answer: B
Each link adds one entry at each end. The link [1, 3] adds 1 to hub 3's list, and the link [3, 4] adds 4. Hub 3 is never in its own list.
Both searches keep a frontier: the hubs found but not yet handled. BFS keeps it in a queue, and DFS keeps it on a stack. On a graph, the only change is where the neighbours of a hub come from.
BFS starts at hub 0 with 0 transfers. It takes the hub at the front of the queue. Each neighbour that is not yet visited gets one more transfer than that hub, and joins the back of the queue.
| Taken from the queue | Hops | New hubs queued |
|---|---|---|
| hub 0 | 0 | 2, 4 |
| hub 2 | 1 | 5 |
| hub 4 | 1 | 3 |
| hub 5 | 2 | 1 |
| hub 3 | 2 | none |
| hub 1 | 3 | none |
Hubs 2 and 4 are one transfer from hub 0. Hub 5 is reached from hub 2, so it gets 2. The other way round the ring, 0, 4, 3, 1, 5, would cost 4. BFS tries both ways at the same pace, so the short way arrives first.
BFS on the network: hubs two and four get one transfer, hub five gets two, and the long way round never matters.
Hubs 6 and 7 never get a number. No chain of links leads to them, so they keep -1. The hop list is [0, 3, 1, 2, 1, 2, -1, -1].
Exercise · Find the bug: Every hub is one hop away. On a chain of hubs, this search reports one hop for every hub it reaches. Which line is wrong?
def bfs_hops(n, links, start):
graph = [[] for _ in range(n)]
for a, b in links:
graph[a].append(b)
graph[b].append(a)
hops = [-1] * n
hops[start] = 0
queue = deque([start])
while queue:
hub = queue.popleft()
for nxt in graph[hub]:
if hops[nxt] == -1:
hops[nxt] = hops[start] + 1
queue.append(nxt)
return hopsNow watch the same walk on a grid. In the player below, every open cell is a hub, and its neighbours are the open cells next to it. Dashed cells are waiting in the queue.
Step by step: BFS on the depot corridors. The animated player loads in your browser.
Predict what happens
Q BFS takes hub 2, at 1 transfer. Hub 5 is open and not yet visited. What number does hub 5 get?
Answer: B
A neighbour is one link further from the start than the hub that found it: 1 + 1 = 2. The number is fixed when the hub joins the queue, and it never changes after that.
Exercise · Predict the output: Hops when a shortcut exists. Six hubs are joined by two routes from hub 0 to hub 3: through hubs 1 and 2, or through hub 4. BFS starts at hub 0 and prints the hops of hubs 0 to 5. What does it print?
from collections import deque
n, links = 6, [[0, 1], [1, 2], [2, 3], [0, 4], [4, 3], [3, 5]]
graph = [[] for _ in range(n)]
for a, b in links:
graph[a].append(b)
graph[b].append(a)
hops = [-1] * n
hops[0] = 0
queue = deque([0])
while queue:
hub = queue.popleft()
for nxt in graph[hub]:
if hops[nxt] == -1:
hops[nxt] = hops[hub] + 1
queue.append(nxt)
print(*hops)DFS starts at hub 0 and pushes it on a stack. It pops the newest hub and pushes each neighbour that is not yet marked. It marks a neighbour at the moment it is pushed, so every hub joins the stack once.
| Popped from the stack | Pushed | Stack after (top on the right) |
|---|---|---|
| hub 0 | 2, 4 | 2, 4 |
| hub 4 | 3 | 2, 3 |
| hub 3 | 1 | 2, 1 |
| hub 1 | 5 | 2, 5 |
| hub 5 | none | 2 |
| hub 2 | none | empty |
DFS visits the hubs in the order 0, 4, 3, 1, 5, 2. It reached hub 5 through hubs 4, 3 and 1, so its route is 0, 4, 3, 1, 5: 4 transfers, not 2. DFS found a route, and BFS found the shortest.
Step by step: DFS on the depot corridors. The animated player loads in your browser.
Look again at hubs 6 and 7. They are linked to each other, and to nothing else. A walk from hub 0 can never reach them, because a walk only follows links. A set of hubs joined by links, with no link to any other hub, is a group.
To count the groups, try every hub in turn. A hub that no earlier walk reached starts a new group: count it, then walk from it.
| Hub tried | Already visited? | Groups so far | Hubs this walk reaches |
|---|---|---|---|
| 0 | no | 1 | 0, 1, 2, 3, 4, 5 |
| 1 | yes | 1 | - |
| 2 | yes | 1 | - |
| 3 | yes | 1 | - |
| 4 | yes | 1 | - |
| 5 | yes | 1 | - |
| 6 | no | 2 | 6, 7 |
| 7 | yes | 2 | - |
The first walk reaches six hubs. Hub 6 is the next hub that is not yet visited, so it starts the second walk. The graph has 2 groups, and the count is the number of walks.
Counting groups: every hub no earlier walk reached starts a new walk, and the number of walks is the number of groups.
Step by step: One walk reaches one depot. The animated player loads in your browser.
Some graphs are never stored. A panel has 3 lamps and 3 buttons. Button 0 flips lamps 0 and 1, button 1 flips lamps 0, 1 and 2, and button 2 flips lamps 1 and 2. A state of the panel is which lamps are on, so there are 8 states.
Each state is a node, and each button leads to another state: that is an edge. The graph exists, but nobody writes it down. This is an implicit graph: a state works out its neighbours when the search needs them.
| Panel state (lamp 2, 1, 0) | Press button 0 | Press button 1 | Press button 2 |
|---|---|---|---|
| 101 | 110 | 010 | 011 |
| 110 | 101 | 001 | 000 |
| 011 | 000 | 100 | 101 |
A button flips lamps, so it is an XOR of the state with a mask. Start with lamps 0 and 2 on, which is state 101. BFS finds the way to all lamps off in 2 presses: 101, 110, 000.
Exercise · Break it: The panel that needs no press. This panel search checks for "all lamps off" when it works out a neighbour, not when it takes a state from the queue. Find a panel where it gives the wrong answer.
def fewest_presses(lamps, start):
buttons = []
for i in range(lamps):
mask = 1 << i
if i > 0:
mask |= 1 << (i - 1)
if i + 1 < lamps:
mask |= 1 << (i + 1)
buttons.append(mask)
presses = [-1] * (1 << lamps)
presses[start] = 0
queue = deque([start])
while queue:
state = queue.popleft()
for mask in buttons:
nxt = state ^ mask
if nxt == 0:
return presses[state] + 1
if presses[nxt] == -1:
presses[nxt] = presses[state] + 1
queue.append(nxt)
return -1Pick a preset, or draw your own walls, and run BFS or DFS. Read each open cell as a hub with up to four neighbours. The counter shows the hubs visited.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Predict what happens
Q A panel has 3 lamps and 3 buttons. How many neighbours does each state have?
Answer: C
Each button leads to exactly one other state, here the state XOR the button's mask. So each state has 3 neighbours, and the 8 states have 12 links in all.
Think about what the queue holds. The start joins at 0 transfers. When BFS takes a hub with d transfers, it adds hubs with d + 1 at the back. So the queue holds hubs with d, then hubs with d + 1, and never three different numbers at once.
Hubs leave the queue in order of their number. Every hub with 2 leaves before any hub with 3.
The queue holds nodes at distance d, then nodes at distance d + 1. So nodes leave in order of distance, and BFS first reaches each node by a route with the fewest links.
This needs every link to cost the same. If links had different costs, a round would no longer mean "equal cost", and Dijkstra's algorithm, in the next module, takes over.
DFS marks a hub when it pushes it, so a hub joins the stack once. It stops only when the stack is empty. Suppose a hub is connected to the start. Follow any route from the start to that hub: the walk cannot finish before it has pushed every neighbour along the route.
DFS marks a node when it is pushed, so each node joins the stack once. It stops only when the stack is empty, so it reaches every node connected to the start.
Every hub joins the frontier once. Every link is looked at twice: once from each end. So both searches cost about n + 2m steps for n hubs and m links. Counting the groups adds no extra cost, because every hub is visited once across all the walks.
Predict what happens
Q A network has 1,000 hubs and 5,000 links. About how many times does BFS look at a neighbour in the adjacency lists?
Answer: C
The adjacency lists hold two entries for every link, one at each end. BFS reads each list once, so it reads 2 × 5,000 = 10,000 entries.
Here is BFS on adjacency lists. It returns the number of transfers from the start to every hub, with -1 for hubs it cannot reach. The step markers [1] to [5] match the steps above.
from collections import deque
def bfs_hops(n, links, start):
# [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
graph = [[] for _ in range(n)]
for a, b in links:
graph[a].append(b)
graph[b].append(a)
# [2] The start hub needs 0 hops and joins the queue; the hops list doubles as the visited marks.
hops = [-1] * n
hops[start] = 0
queue = deque([start])
while queue:
# [3] Take the oldest hub from the front of the queue.
hub = queue.popleft()
# [4] Each neighbour not visited yet gets one more hop and joins the back.
for nxt in graph[hub]:
if hops[nxt] == -1:
hops[nxt] = hops[hub] + 1
queue.append(nxt)
# [5] Every reachable hub has its hop count; hubs in other groups keep -1.
return hopspublic int[] bfsHops(int n, int[][] links, int start) {
// [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
List<Integer>[] graph = new List[n];
for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
for (int[] link : links) {
graph[link[0]].add(link[1]);
graph[link[1]].add(link[0]);
}
// [2] The start hub needs 0 hops and joins the queue; the hops list doubles as the visited marks.
int[] hops = new int[n];
Arrays.fill(hops, -1);
hops[start] = 0;
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
while (!queue.isEmpty()) {
// [3] Take the oldest hub from the front of the queue.
int hub = queue.poll();
// [4] Each neighbour not visited yet gets one more hop and joins the back.
for (int nxt : graph[hub]) {
if (hops[nxt] == -1) {
hops[nxt] = hops[hub] + 1;
queue.add(nxt);
}
}
}
// [5] Every reachable hub has its hop count; hubs in other groups keep -1.
return hops;
}vector<int> bfsHops(int n, vector<vector<int>> links, int start) {
// [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
vector<vector<int>> graph(n);
for (auto& link : links) {
graph[link[0]].push_back(link[1]);
graph[link[1]].push_back(link[0]);
}
// [2] The start hub needs 0 hops and joins the queue; the hops list doubles as the visited marks.
vector<int> hops(n, -1);
hops[start] = 0;
queue<int> q;
q.push(start);
while (!q.empty()) {
// [3] Take the oldest hub from the front of the queue.
int hub = q.front();
q.pop();
// [4] Each neighbour not visited yet gets one more hop and joins the back.
for (int nxt : graph[hub]) {
if (hops[nxt] == -1) {
hops[nxt] = hops[hub] + 1;
q.push(nxt);
}
}
}
// [5] Every reachable hub has its hop count; hubs in other groups keep -1.
return hops;
}function bfsHops(n, links, start) {
// [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
const graph = Array.from({ length: n }, () => []);
for (const [a, b] of links) {
graph[a].push(b);
graph[b].push(a);
}
// [2] The start hub needs 0 hops and joins the queue; the hops list doubles as the visited marks.
const hops = new Array(n).fill(-1);
hops[start] = 0;
const queue = [start];
let head = 0;
while (head < queue.length) {
// [3] Take the oldest hub from the front of the queue.
const hub = queue[head++];
// [4] Each neighbour not visited yet gets one more hop and joins the back.
for (const nxt of graph[hub]) {
if (hops[nxt] === -1) {
hops[nxt] = hops[hub] + 1;
queue.push(nxt);
}
}
}
// [5] Every reachable hub has its hop count; hubs in other groups keep -1.
return hops;
}The hops list does two jobs, as dist did on the grid. It stores each number of transfers, and a value other than -1 also means "visited".
Here is DFS used to count groups. It tries every hub, and starts a walk from each hub that no earlier walk reached. The walk uses an explicit stack, so a chain of 100,000 hubs cannot overflow the call stack.
def count_groups(n, links):
# [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
graph = [[] for _ in range(n)]
for a, b in links:
graph[a].append(b)
graph[b].append(a)
# [2] No hub is visited yet, and no group is counted yet.
seen = [False] * n
groups = 0
for hub in range(n):
if seen[hub]:
continue
# [3] A hub no earlier walk reached starts a new group: count it, mark it and push it.
groups += 1
seen[hub] = True
stack = [hub]
while stack:
# [4] Pop the newest hub, and push each neighbour not visited yet, marking it as it is pushed.
current = stack.pop()
for nxt in graph[current]:
if not seen[nxt]:
seen[nxt] = True
stack.append(nxt)
# [5] Every hub belongs to a counted group: the count is the answer.
return groupspublic int countGroups(int n, int[][] links) {
// [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
List<Integer>[] graph = new List[n];
for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
for (int[] link : links) {
graph[link[0]].add(link[1]);
graph[link[1]].add(link[0]);
}
// [2] No hub is visited yet, and no group is counted yet.
boolean[] seen = new boolean[n];
int groups = 0;
int[] stack = new int[n];
for (int hub = 0; hub < n; hub++) {
if (seen[hub]) continue;
// [3] A hub no earlier walk reached starts a new group: count it, mark it and push it.
groups++;
seen[hub] = true;
int top = 0;
stack[top++] = hub;
while (top > 0) {
// [4] Pop the newest hub, and push each neighbour not visited yet, marking it as it is pushed.
int current = stack[--top];
for (int nxt : graph[current]) {
if (!seen[nxt]) {
seen[nxt] = true;
stack[top++] = nxt;
}
}
}
}
// [5] Every hub belongs to a counted group: the count is the answer.
return groups;
}int countGroups(int n, vector<vector<int>> links) {
// [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
vector<vector<int>> graph(n);
for (auto& link : links) {
graph[link[0]].push_back(link[1]);
graph[link[1]].push_back(link[0]);
}
// [2] No hub is visited yet, and no group is counted yet.
vector<bool> seen(n, false);
int groups = 0;
for (int hub = 0; hub < n; hub++) {
if (seen[hub]) continue;
// [3] A hub no earlier walk reached starts a new group: count it, mark it and push it.
groups++;
seen[hub] = true;
vector<int> stack = {hub};
while (!stack.empty()) {
// [4] Pop the newest hub, and push each neighbour not visited yet, marking it as it is pushed.
int current = stack.back();
stack.pop_back();
for (int nxt : graph[current]) {
if (!seen[nxt]) {
seen[nxt] = true;
stack.push_back(nxt);
}
}
}
}
// [5] Every hub belongs to a counted group: the count is the answer.
return groups;
}function countGroups(n, links) {
// [1] Build the adjacency lists: a two-way link is a neighbour entry at both hubs.
const graph = Array.from({ length: n }, () => []);
for (const [a, b] of links) {
graph[a].push(b);
graph[b].push(a);
}
// [2] No hub is visited yet, and no group is counted yet.
const seen = new Array(n).fill(false);
let groups = 0;
for (let hub = 0; hub < n; hub++) {
if (seen[hub]) continue;
// [3] A hub no earlier walk reached starts a new group: count it, mark it and push it.
groups++;
seen[hub] = true;
const stack = [hub];
while (stack.length) {
// [4] Pop the newest hub, and push each neighbour not visited yet, marking it as it is pushed.
const current = stack.pop();
for (const nxt of graph[current]) {
if (!seen[nxt]) {
seen[nxt] = true;
stack.push(nxt);
}
}
}
}
// [5] Every hub belongs to a counted group: the count is the answer.
return groups;
}The last template is BFS on an implicit graph. Nothing is stored: step [1] only works out the buttons as masks, and step [4] computes each neighbour as state ^ mask.
from collections import deque
def fewest_presses(lamps, start):
# [1] Each button flips its own lamp and the lamps beside it: a button is a bit mask to XOR with the state.
buttons = []
for i in range(lamps):
mask = 1 << i
if i > 0:
mask |= 1 << (i - 1)
if i + 1 < lamps:
mask |= 1 << (i + 1)
buttons.append(mask)
# [2] The starting panel needs 0 presses and joins the queue; the presses list doubles as the visited marks.
presses = [-1] * (1 << lamps)
presses[start] = 0
queue = deque([start])
while queue:
# [3] Take the oldest panel state; all lamps off ends the search.
state = queue.popleft()
if state == 0:
return presses[state]
# [4] Each button leads to a neighbour state; an unvisited one gets one more press and joins the back.
for mask in buttons:
nxt = state ^ mask
if presses[nxt] == -1:
presses[nxt] = presses[state] + 1
queue.append(nxt)
# [5] The queue ran dry with some lamp still on: no sequence of presses switches them all off.
return -1public int fewestPresses(int lamps, int start) {
// [1] Each button flips its own lamp and the lamps beside it: a button is a bit mask to XOR with the state.
int[] buttons = new int[lamps];
for (int i = 0; i < lamps; i++) {
int mask = 1 << i;
if (i > 0) mask |= 1 << (i - 1);
if (i + 1 < lamps) mask |= 1 << (i + 1);
buttons[i] = mask;
}
// [2] The starting panel needs 0 presses and joins the queue; the presses list doubles as the visited marks.
int[] presses = new int[1 << lamps];
Arrays.fill(presses, -1);
presses[start] = 0;
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
while (!queue.isEmpty()) {
// [3] Take the oldest panel state; all lamps off ends the search.
int state = queue.poll();
if (state == 0) return presses[state];
// [4] Each button leads to a neighbour state; an unvisited one gets one more press and joins the back.
for (int mask : buttons) {
int nxt = state ^ mask;
if (presses[nxt] == -1) {
presses[nxt] = presses[state] + 1;
queue.add(nxt);
}
}
}
// [5] The queue ran dry with some lamp still on: no sequence of presses switches them all off.
return -1;
}int fewestPresses(int lamps, int start) {
// [1] Each button flips its own lamp and the lamps beside it: a button is a bit mask to XOR with the state.
vector<int> buttons;
for (int i = 0; i < lamps; i++) {
int mask = 1 << i;
if (i > 0) mask |= 1 << (i - 1);
if (i + 1 < lamps) mask |= 1 << (i + 1);
buttons.push_back(mask);
}
// [2] The starting panel needs 0 presses and joins the queue; the presses list doubles as the visited marks.
vector<int> presses(1 << lamps, -1);
presses[start] = 0;
queue<int> q;
q.push(start);
while (!q.empty()) {
// [3] Take the oldest panel state; all lamps off ends the search.
int state = q.front();
q.pop();
if (state == 0) return presses[state];
// [4] Each button leads to a neighbour state; an unvisited one gets one more press and joins the back.
for (int mask : buttons) {
int nxt = state ^ mask;
if (presses[nxt] == -1) {
presses[nxt] = presses[state] + 1;
q.push(nxt);
}
}
}
// [5] The queue ran dry with some lamp still on: no sequence of presses switches them all off.
return -1;
}function fewestPresses(lamps, start) {
// [1] Each button flips its own lamp and the lamps beside it: a button is a bit mask to XOR with the state.
const buttons = [];
for (let i = 0; i < lamps; i++) {
let mask = 1 << i;
if (i > 0) mask |= 1 << (i - 1);
if (i + 1 < lamps) mask |= 1 << (i + 1);
buttons.push(mask);
}
// [2] The starting panel needs 0 presses and joins the queue; the presses list doubles as the visited marks.
const presses = new Array(1 << lamps).fill(-1);
presses[start] = 0;
const queue = [start];
let head = 0;
while (head < queue.length) {
// [3] Take the oldest panel state; all lamps off ends the search.
const state = queue[head++];
if (state === 0) return presses[state];
// [4] Each button leads to a neighbour state; an unvisited one gets one more press and joins the back.
for (const mask of buttons) {
const nxt = state ^ mask;
if (presses[nxt] === -1) {
presses[nxt] = presses[state] + 1;
queue.push(nxt);
}
}
}
// [5] The queue ran dry with some lamp still on: no sequence of presses switches them all off.
return -1;
}Now write both searches yourself, for the hub network of a parcel-delivery app. The lab has two functions. Each test gives your function the number of hubs and the list of links.
fewest_transfers(n, links, start, goal): return the fewest links on any route from start to goal with BFS, or -1 when no route exists.reachable_hubs(n, links, start): return every hub reachable from start, start included, in ascending order. Use DFS with an explicit stack, not recursion.When a test fails, the result shows the network, what your function returned and what it should return. A note says what that test is checking.
Three rules keep both functions correct:
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | BFS | DFS |
|---|---|---|
| Time | O(n + m): each node joins once and each link is read from both ends | O(n + m): each node is pushed once and each link is read from both ends |
| Memory | O(n) for the marks; the queue holds about one round of nodes | O(n) for the marks; the stack can hold almost every node on one long route |
| Fewest links when every link costs the same | Yes: the first visit is the shortest | No: the first route found can be long |
| The frontier | A queue: the oldest node first | A stack or the call stack: the newest node first |
| Reaches | Every node connected to the start | Every node connected to the start |
For 100,000 nodes and 200,000 links, that is about 500,000 steps, which any of the four languages runs in well under a second.
Use BFS when the question says "fewest links", "fewest moves" or "how many rounds". Each link must cost the same. It also works on implicit graphs, such as lock codes or lamp panels, where the states are computed.
Use DFS, or BFS, when you need every connected node: is there a route at all, how many groups are there, or copy everything the root can reach. Both visit the same nodes. DFS with a stack is the base of backtracking and cycle checks later in this module.
Do not use BFS for "cheapest" routes when links cost different amounts. Rounds count links, not cost. Dijkstra's algorithm, in the next module, handles that.
Do not use DFS for "fewest links" at all. And an implicit graph with billions of states, such as a large puzzle, makes BFS run out of memory. That needs a smarter search, which is a later topic.
Writing only graph[a].append(b) makes the link one-way. Counterexample: n = 2, links = [[0, 1]], start = 1 must give the hops [1, 0], but the one-way lists give [-1, 0], because hub 0 is not in hub 1's list. Add graph[b].append(a) as well.
A link added to one list only is a one-way road: a walk from the other end finds nothing.
If BFS marks a hub when it is taken out, as in hub = queue.popleft(); done[hub] = True, a hub can join the queue once for each neighbour that finds it first. On 6 hubs with all 15 links, the queue receives 16 entries instead of 6. Mark the hub at the moment you append it.
A single walk from hub 0 reaches only its own group. On the lesson's network it visits 6 hubs and stops, so groups = 1 is wrong: the answer is 2. The loop for hub in range(n) with if seen[hub]: continue is what finds the other groups.
Take a panel of 2 lamps, where both buttons flip both lamps. From state 01, all lamps off can never be reached. Without presses[nxt] == -1, the search never stops: round 10 alone queues 2^10 = 1,024 entries, and each round doubles. Always keep a visited table, whatever the graph looks like.
O(n + m). Mark nodes as they join the frontier, and keep a visited table even on implicit graphs.Explain the two searches on a graph in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Graphs and lists
Q1/2 The link [2, 5] joins two hubs in both directions. How does an adjacency list store it?
Answer: B
An adjacency list gives each hub the list of its neighbours. A two-way link makes each end a neighbour of the other, so it adds one entry at each end.
Q2/2 How is finding neighbours on a graph different from finding them on a grid?
Answer: B
The grid's four moves are a rule. A stored graph keeps a list for each node, and an implicit graph computes the neighbours of a state. The rest of BFS and DFS does not change.
Checkpoint · How the searches move
Q1/2 On the lesson's network, how many transfers does BFS find from hub 0 to hub 5?
Answer: A
Hub 5 is reached through hub 2, in 2 transfers. The other way round the ring, through hubs 4, 3 and 1, needs 4, and BFS tries both ways at the same pace.
Q2/2 DFS reached hub 5 by a route of 4 transfers, and BFS by a route of 2. Why do they differ?
Answer: C
DFS goes deep along one route, and that route happened to be the long way round. BFS spreads in rounds, so the shortest route arrives first. Both visit the same hubs.
Checkpoint · Counting groups
Q1/2 A network has 6 hubs and no links at all. How many groups does it have?
Answer: C
A hub with no links is still a group: a set of hubs with no link to any other hub. Each of the 6 hubs starts a walk, so the count is 6.
Q2/2 Why does the group-counting code try every hub, instead of one walk from hub 0?
Answer: B
One walk follows links, and links never lead out of a group. So hubs in other groups need their own walks. A hub that is already marked belongs to a group that is already counted.
Checkpoint · Implicit graphs and marking
Q1/2 A panel has 3 lamps and 3 buttons, and each button changes the lamps beside it. In the search, what is a node and what is an edge?
Answer: B
There are 8 states of 3 lamps. A press leads from one state to another, so each press is an edge. Nothing is stored: the state works out its neighbours as state ^ mask.
Q2/2 Why must BFS mark a node when it joins the queue, not when it leaves?
Answer: B
On a graph with many links, a node can be found by several neighbours before it leaves the queue. Marking when it joins means each node joins once. On 6 hubs with all 15 links, marking late puts 16 entries in the queue instead of 6.
Checkpoint · Cost and mistakes
Q1/2 A network has n hubs and m links. What does BFS or DFS cost?
Answer: C
Each hub is queued or pushed once, and each of the 2m entries in the adjacency lists is read once. That is about n + 2m steps.
Q2/2 A link [a, b] is added with graph[a].append(b) only. What goes wrong for n = 2, links = [[0, 1]], start = 1?
Answer: B
The link works in both directions, so both lists need it. With only one list, a walk from hub 1 finds no neighbours and leaves hub 0 at -1, where the correct answer is 1.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.