Search and backtracking · 11 / 15 Exercise Hard

The N queens problem

Objective

Create a Python program that solves the classic N queens problem: place n queens on an n × n board so that none attack each other (not on the same row, the same column or a diagonal).

Instructions

  • Read an integer n between 1 and 8.
  • Place the queens row by row: in row row try the columns from 1 to n in order. A column is safe if no previous queen is in that column or on a diagonal (same difference in columns as in rows). If it is safe, place it and go on; when coming back, remove it (backtracking).
  • Each solution is the list of the queens' columns, one per row. Show Solutions: t with the total number of solutions and First solution: c1 c2 ... cn with the first one you find, or No solution if there are none.
Input
4
Output
Solutions: 2
First solution: 2 4 1 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise