-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_v2.py
46 lines (38 loc) · 1.18 KB
/
example_v2.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
# Number of queens
print("Enter the number of queens")
N = int(input())
# chessboard
# NxN matrix with all elements 0
board = [[0]*N for _ in range(N)]
def is_attack(i, j):
# checking if there is a queen in row or column
for k in range(0, N):
if board[i][k] == 1 or board[k][j] == 1:
return True
# checking diagonals
for k in range(0, N):
for l in range(0, N):
if (k+l == i+j) or (k-l == i-j):
if board[k][l] == 1:
return True
return False
def N_queen(n):
# if n is 0, solution found
if n == 0:
return True
for i in range(0, N):
for j in range(0, N):
'''checking if we can place a queen here or not
queen will not be placed if the place is being attacked
or already occupied'''
if (not(is_attack(i, j))) and (board[i][j] != 1):
board[i][j] = 1
# recursion
# wether we can put the next queen with this arrangment or not
if N_queen(n-1) == True:
return True
board[i][j] = 0
return False
N_queen(N)
for i in board:
print(i)