forked from tasha06/Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN_Queens
34 lines (27 loc) · 773 Bytes
/
N_Queens
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
print('Number of queens: ')
n= int(input())
board = [[0]*n for _ in range(n)]
def is_attack(i, j):
for k in range(0, n):
if board[i][k]==1 or board[k][j] == 1:
return True
for k in range(0, n):
for l in range(0,n):
if(k+1 ==i+j) or (k-l == i-j):
if board[k][l]==1:
return True
return False
def n_queens(n):
if n==0:
return True
for i in range(0, n):
for j in range(0,n):
if (not(is_attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if n_queens(n-1) == True:
return True
board[i][j] = 0
return False
n_queens(n)
for i in board:
print(i)