-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnQueen.py
More file actions
48 lines (40 loc) · 1.1 KB
/
nQueen.py
File metadata and controls
48 lines (40 loc) · 1.1 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def queens(n):
board = [ ['.' for _ in range(n)] for _ in range(n)]
solution =[]
def is_valid(row , col):
# check col
for i in range(row):
if board[i][col]=='Q':
return False
# check right dai
i, j = row-1,col-1
while i >=0 and j >= 0:
if board[i][j] == 'Q':
return False
i -=1
j -=1
i, j = row-1,col+1
while i >=0 and j < n:
if board[i][j] == 'Q':
return False
i-=1
j+=1
return True
def backtrack(row):
if row == n:
current=[]
for r in board:
current.append(".".join(r))
solution.append(current)
return
for col in range(n):
if is_valid(row , col):
board[row][col]= 'Q'
backtrack(row+1)
board[row][col]='.'
backtrack(0)
return solution
solution =queens(4)
for i in solution:
for j in i:
print(j)