Boss lesson · Unit 04
N-Queens
One queen per row, three sets, no attacks
What you practise
- Row by row with column and diagonal sets
- 4 queens has 2 solutions
Try a question from this lesson
Pick one
Four queens must sit on a 4×4 board so that no two share a row, a column or a diagonal. How many queens end up in each row?
Correct answer
Exactly one
Why
Two queens in one row attack each other, so a row holds at most one. Four queens in four rows then forces exactly one each. The puzzle becomes four choices: which column for each row.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Row by row
Place the queens one row at a time. In each row, try every column.
If a square is safe: choose it, explore the next row, then undo it and try the next column. That is choose, explore, undo, with rows as the depth.
If no square in a row is safe, the call simply returns. The row before it moves its queen and the search carries on. Reaching row n means every row got a queen: one solution, like the board shown here.
col 0 1 2 3
row 0 . Q . .
row 1 . . . Q
row 2 Q . . .
row 3 . . Q .col 0 1 2 3
row 0 . Q . .
row 1 . . . Q
row 2 Q . . .
row 3 . . Q .col 0 1 2 3
row 0 . Q . .
row 1 . . . Q
row 2 Q . . .
row 3 . . Q .Concept
Three sets
Comparing a square with every earlier queen works, but remembering what is taken is faster.
Keep three sets. cols holds the used columns. diag holds row − col for every queen: one number per ↘ diagonal. anti holds row + col: one number per ↙ diagonal.
A square is free when none of its three numbers is in its set. Placing a queen adds three numbers, and the undo removes them.
cols, diag, anti = set(), set(), set()
def mark(r, c):
cols.add(c)
diag.add(r - c)
anti.add(r + c)
def free(r, c):
if c in cols:
return False
if r - c in diag:
return False
return r + c not in anticonst cols = new Set();
const diag = new Set();
const anti = new Set();
function mark(r, c) {
cols.add(c);
diag.add(r - c);
anti.add(r + c);
}
function free(r, c) {
if (cols.has(c)) return false;
if (diag.has(r - c)) return false;
return !anti.has(r + c);
}const cols = new Set<number>();
const diag = new Set<number>();
const anti = new Set<number>();
function mark(r: number, c: number) {
cols.add(c);
diag.add(r - c);
anti.add(r + c);
}
function free(r: number, c: number) {
if (cols.has(c)) return false;
if (diag.has(r - c)) return false;
return !anti.has(r + c);
}Python notex in s on a set is one hash lookup, however many items the set holds. On a list it would scan every item.
TypeScript notenew Set<number>() says the set will hold numbers. An empty new Set() gives TypeScript nothing to infer the item type from.
10 more exercises in the app
- 4× multiple choice
- 2× type the answer
- 2× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.