

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
Brute force wastes a lot of effort building boards that are obviously doomed. Take this partial layout:
[1, 3]
If we try to place the next queen at row 2, column 1, we don't need to look any further to know it's bad – it shares a column with the queen in row 0:
[1, 3, 1]
Row 2, column 2 is no good either because now it's on the same diagonal as the queen in row 1:
[1, 3, 2]
Instead of checking a full board after it's complete, we can check each new position before we commit to it:
is_valid_board checks whether a finished board is valid.is_safe – checks whether one proposed position is okay given the partial board we've built so far.If a position is unsafe, we can skip it immediately. There's no reason to keep building on a board layout that's already guaranteed to fail.
Complete the is_safe function. It accepts:
board: a partial board represented as a list[int]row: the row where we might place the next queencol: the column where we might place the next queenIt should return True if the position is safe, otherwise False. This function should not change the board; it only answers whether appending col for the given row would create a conflict.