Place n queens on an n × n chessboard so that no two queens attack each other: no two share a row, a column or a diagonal.
What to build
A program that counts the solutions and prints the first one.
Requirements
- Print the number of solutions.
- Print the first solution in lexicographic order as the column (from 1) of the queen in each row, or
nonewhen there is no solution.
Input
One integer n.
Output
Two lines: the number of solutions, then the first solution or none.
Constraints
1 ≤ n ≤ 8.
Example
Input:
4
Output:
2
2 4 1 3
Why it works
Placing queens row by row and pruning every column or diagonal already attacked cuts the search tree to a few thousand nodes for n = 8. Trying columns from the left makes the first solution found the smallest.
Examples
4
2 2 4 1 3
1
1 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Place one queen per row. Keep sets of used columns and of the two diagonals (row − col and row + col).
Hint 2
Try the columns of a row from left to right, so the first full solution you find is the smallest one.
Hint 3
Count every solution, but remember only the first.
Solution
Show one correct solution (try it yourself first)
n = int(input())
cols = set()
d1 = set()
d2 = set()
path = []
count = 0
first = None
def place(row):
global count, first
if row == n:
count += 1
if first is None:
first = path[:]
return
for c in range(n):
if c in cols or row - c in d1 or row + c in d2:
continue
cols.add(c)
d1.add(row - c)
d2.add(row + c)
path.append(c + 1)
place(row + 1)
path.pop()
cols.remove(c)
d1.remove(row - c)
d2.remove(row + c)
place(0)
print(count)
print(*first if first else ["none"])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step