| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| def n_queens(n, width):
if n == 0:
return [[]] # one solution, the empty list
else:
return add_queen(n-1, width, n_queens(n-1, width))
def add_queen(new_row, width, previous_solutions):
solutions = []
for sol in previous_solutions:
for new_col in range(width):
if safe_queen(new_row, new_col, sol):
solutions.append(sol + [new_col])
return solutions
def safe_queen(new_row, new_col, sol):
for row in range(new_row):
if (sol[row] == new_col or
sol[row] + row == new_col + new_row or
sol[row] - row == new_col - new_row):
return 0
return 1
for sol in n_queens(8, 8):
print sol |