Skip to content

Commit

Permalink
Merge pull request #382 from Vidhi-bhutia/patch-2
Browse files Browse the repository at this point in the history
Create N-Queens.py
  • Loading branch information
Kavya-24 authored Oct 5, 2024
2 parents 19a5ff1 + aa2eace commit 19867e4
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions Artificial Intelligence/N-Queens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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()

0 comments on commit 19867e4

Please sign in to comment.