-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn-queens.py
57 lines (53 loc) · 1.26 KB
/
n-queens.py
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
49
50
51
52
53
54
55
56
57
'''
N-Queens- python solution
n -> n creates n*n board
'''
n = 4
board = [['.' for i in range(n)] for j in range(n)]
def print_board(board):
for b in board:
print('|',end=' ')
for element in b:
if element == '.':
print('.', end=' ')
else:
print('Q', end=' ')
print('|')
print()
def check(board,r,c,n):
for row in range(0, n):
if board[row][c] == 'Q':
return False
for col in range(0, n):
if board[r][col] == 'Q':
return False
row, col = r - 1, c - 1
while row >= 0 and col >= 0:
if board[row][col] == 'Q':
return False
row -= 1
col -= 1
row, col = r - 1, c + 1
while row >= 0 and col < n:
if board[row][col] == 'Q':
return False
row -= 1
col += 1
return True
def fun(board,r,n):
if r == n:
#for b in board:
# print(b)
#print()
print_board(board)
return 1
count = 0
for c in range(0,n):
if not board[r][c]:
continue
if check(board,r,c,n):
board[r][c] = 'Q'
count += fun(board,r+1,n)
board[r][c] = '.'
return count
print(fun(board,0,n))