

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: N Queens
incomplete
2: Validate Boards
incomplete
3: First Solution
incomplete
4: All Solutions
incomplete
5: Safe Positions
incomplete
6: Backtracking
incomplete
7: Pruning
incomplete
8: Complexity
incomplete
This lesson's interactive features are locked, please to keep using them
The N Queens problem is a classic for a reason. It has a reputation for being nasty, and often shows up in software engineering interviews.
N Queens is useful because it's the perfect excuse to practice a core DS&A pattern: hunting through many possible states while leaning on constraints, backtracking, and pruning to skip work we don't need to do. Here's the question:
How can we place
nqueens on ann × nchessboard so that no two queens can attack each other?
The queen is the most powerful chess piece. She can attack anywhere along:
For a tiny 4 × 4 board, one arrangement of queens that solves the problem looks like this:
No two queens share a row, column, or diagonal.
Sounds easy, right? Right...
Here's our first constraint: a valid solution has exactly one queen in each row. If two queens shared a row, they'd be attacking each other before we even got started.
So, a simple brute-force search can go row by row:
012Each row has n possible columns. So the number of boards we might build before checking which ones actually pass is:
n * n * n * ... * n
Or, more compactly:
n**n
For an 8 × 8 board, that's 16,777,216 arrangements, and it only gets worse from here! The whole point of this challenge is to avoid as much of that work as we possibly can.
We'll represent a "candidate board" as a list of column positions. Each index in the list is a row, and the value at that index is the column where the queen sits in that row. Again, this board:
Will be represented as:
[1, 3, 0, 2]
0 has a queen in column 11 has a queen in column 32 has a queen in column 03 has a queen in column 2Complete the get_candidate_boards function. It accepts a board size n (an int) and returns every possible board with exactly one queen in each row (a list[list[int]]).
The boards should be in lexicographic order, which happens naturally if you build them row by row and try columns from left to right. For example, if n=2, the return value should be:
[
[0, 0],
[0, 1],
[1, 0],
[1, 1],
]