-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchalenge11.py
More file actions
32 lines (32 loc) · 947 Bytes
/
chalenge11.py
File metadata and controls
32 lines (32 loc) · 947 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def solveNQueens(n):
queen = [['.'] * n for _ in range(n)]
answers = []
cols = [-1] * n
row = 0
while row >= 0:
if cols[row] != -1:
queen[row][cols[row]] = '.'
placed = False
start_col = cols[row] + 1
for col in range(start_col, n):
safe = True
for r in range(row):
if cols[r] == col or abs(cols[r] - col) == abs(r - row):
safe = False
break
if safe:
cols[row] = col
queen[row][col] = 'Q'
placed = True
if row == n - 1:
answers.append([''.join(r) for r in queen])
else:
row += 1
cols[row] = -1
break
if not placed:
cols[row] = -1
row -= 1
return answers
solutions = solveNQueens(4)
print(solutions)