-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueen.py
67 lines (61 loc) · 1.4 KB
/
queen.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
58
59
60
61
62
63
64
65
66
67
def is_safe(board, row, col, N):
for i in range(col):
if board[row][i] == 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 j >= 0 and i < N:
if board[i][j] == 1:
return False
i += 1
j -= 1
return True
def solve_n_queen_until(board,col,N,solutions):
if col == N:
solution=[]
for i in range(N):
row=[]
for j in range(N):
row.append(board[i][j])
solution.append(row)
solutions.append(solution)
return
for i in range(N):
if is_safe(board,i,col,N):
board[i][col]=1
solve_n_queen_until(board,col+1,N,solutions)
board[i][col]=0
def solve_n_queen(N):
board = [[0] * N for _ in range (N)]
solutions=[]
solve_n_queen_until(board,0,N,solutions)
if len(solutions) == 0:
print(" Not Possible ")
else:
for solution in solutions:
for row in solution:
for cell in row:
print("Q" if cell == 1 else ".", end=" ")
print()
print()
#N=4
N=int(input("Enter no of Queens: "))
solve_n_queen(N)
"""
Enter no of Queens: 4
. . Q .
Q . . .
. . . Q
. Q . .
. Q . .
. . . Q
Q . . .
. . Q .
"""