-
Notifications
You must be signed in to change notification settings - Fork 0
/
nq.py
40 lines (38 loc) · 932 Bytes
/
nq.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
def is_safe(board, row, col, n):
for c in range(col):
if board[row][c] == 1:
return False
i = row
j = col
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1
i = row
j = col
while i < n and j >= 0:
if board[i][j] == 1:
return False
i += 1
j -= 1
return True
def nQueens(board, col, n):
if col >= n:
return True
for i in range(n):
if is_safe(board, i, col, n):
board[i][col] = 1
if nQueens(board, col + 1, n):
return True
board[i][col] = 0
return False
n = int(input())
board = [[0 for j in range(n)] for i in range(n)]
if nQueens(board, 0, n) == True:
for i in range(n):
for j in range(n):
print(board[i][j], end=" ")
print()
else:
print("Not possible to place queens")