-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN Queens.py
More file actions
46 lines (40 loc) · 1.27 KB
/
N Queens.py
File metadata and controls
46 lines (40 loc) · 1.27 KB
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
# N Queens Problem - User-defined N
def print_solution(board, N):
for i in range(N):
for j in range(N):
print(board[i][j], end=' ')
print()
print() # blank line between solutions
def is_safe(board, row, col, N):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_nq_util(board, col, N):
# Base case: If all queens are placed
if col >= N:
print_solution(board, N)
return True
res = False
for i in range(N):
if is_safe(board, i, col, N):
board[i][col] = 1
res = solve_nq_util(board, col + 1, N) or res
board[i][col] = 0 # Backtrack
return res
def solve_nq(N):
board = [[0 for _ in range(N)] for _ in range(N)]
if not solve_nq_util(board, 0, N):
print("No solution exists for N =", N)
# --- Main program ---
N = int(input("Enter number of queens (N): "))
solve_nq(N)