This repository has been archived by the owner on Oct 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
N-Queens.py
56 lines (46 loc) · 1.39 KB
/
N-Queens.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
def print_board(board):
for row in board:
print(" ".join("Q" if cell else "." for cell in row))
print()
def is_safe(board, row, col):
for i in range(row):
if board[i][col]:
return False
i, j = row, col
while i >= 0 and j >= 0:
if board[i][j]:
return False
i -= 1
j -= 1
i, j = row, col
while i >= 0 and j < len(board):
if board[i][j]:
return False
i -= 1
j += 1
return True
def solve_queens(board, row, solutions):
if row >= len(board):
solutions.append([row[:] for row in board])
return
for col in range(len(board)):
if is_safe(board, row, col):
board[row][col] = True
solve_queens(board, row + 1, solutions)
board[row][col] = False
def eight_queens():
size = int(input("Enter size of the board: "))
while (size < 0):
print("Please enter a positive number! ")
size = int(input("Enter size of the board: "))
board = [[False for _ in range(size)] for _ in range(size)]
solutions = []
solve_queens(board, 0, solutions)
if not solutions:
print("No solution exists.")
else:
print(f"Found {len(solutions)} solutions:")
for i, solution in enumerate(solutions):
print(f"Solution {i + 1}:")
print_board(solution)
eight_queens()