Boss lesson · Unit 01
Grids are graphs
Find the neighbours of a cell without leaving the grid
What you practise
- Neighbours from direction deltas
- Bounds checks
Try a question from this lesson
Pick one
A robot moves one cell up, down, left or right. It stands in the top-left corner of a 3 × 3 grid. How many moves can it make?
Correct answer
2
Why
From a corner only right and down stay on the grid. Every cell is a node and every legal move is an edge, so a grid is a graph, even though nobody wrote its edges down.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Neighbours from directions
A grid needs no adjacency list. The neighbours of cell (r, c) are found by adding a direction to it: one row up, one row down, one column left, one column right.
Keep the four directions in a list and loop over them.
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
r, c = 1, 1
for dr, dc in DIRS:
print(r + dr, c + dc)const DIRS = [
[-1, 0], [1, 0], [0, -1], [0, 1],
];
const r = 1, c = 1;
for (const [dr, dc] of DIRS) {
console.log(r + dr, c + dc);
}const DIRS = [
[-1, 0], [1, 0], [0, -1], [0, 1],
];
const r = 1, c = 1;
for (const [dr, dc] of DIRS) {
console.log(r + dr, c + dc);
}9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.