The problem
Return the number of ways to place n queens on an n × n board so that no two share a row, a column or a diagonal. Lesson 5 explains the rules and the search.
n_queens(4) # 2
n_queens(8) # 92
n_queens(3) # 0
Limits
nis from 1 to 10.
Builds on RECR-5 Pruning.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
6 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | 4 by 4 | Not run | |
| 2 | 1 by 1 | Not run | |
| 3 | 2 and 3 | Not run | |
| 4 | 6 by 6 | Not run | |
| 5 | 8 by 8 | Not run | |
| 6 | 10 by 10 | Not run |