0% found this document useful (0 votes)
0 views

AI Assignment 4

The document contains a Python implementation of the N-Queens problem using backtracking. It includes functions to print the chessboard, check if a queen can be safely placed, and recursively solve the problem. The program prompts the user for the board size and handles cases for valid and invalid inputs.

Uploaded by

sohamsaradecomp
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

AI Assignment 4

The document contains a Python implementation of the N-Queens problem using backtracking. It includes functions to print the chessboard, check if a queen can be safely placed, and recursively solve the problem. The program prompts the user for the board size and handles cases for valid and invalid inputs.

Uploaded by

sohamsaradecomp
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

AI Assignment 4

N-Queen’s Problem
Code:
def print_solution(board):
"""Function to print the chessboard solution."""
for row in board:
print(" ".join("Q" if cell else "_" for cell in row))
print() # Print a newline for better readability

def is_safe(board, row, col, N):


"""Function to check if a queen can be placed at board[row][col]."""

# Check the current column upwards


for i in range(row):
if board[i][col]:
return False

# Check upper-left diagonal


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j]:
return False

# Check upper-right diagonal


for i, j in zip(range(row, -1, -1), range(col, N)):
if board[i][j]:
return False

return True # If no conflicts, the position is safe

def solve_n_queens(board, row, N):


"""Recursive function to solve the N-Queens problem using backtracking."""

# Base case: If all queens are placed, print the solution


if row == N:
print_solution(board)
return True # Return True to indicate a solution is found

found_solution = False # To track if at least one solution exists

# Try placing a queen in each column of the current row


for col in range(N):
if is_safe(board, row, col, N): # Check if placing is valid
board[row][col] = True # Place the queen

# Recur for the next row


if solve_n_queens(board, row + 1, N):
found_solution = True # Mark that a solution is found

board[row][col] = False # Backtrack (remove the queen)

return found_solution # Return True if at least one solution exists

# Take user input for board size


N = int(input("Enter the size of the chessboard (N): "))
if N < 10:
# Initialize an N x N board with False (no queens placed)
board = [[False] * N for _ in range(N)]

# Start solving from the first row


if not solve_n_queens(board, 0, N):
print("No solution exists.")

else:
print("Oops! Board size is too large. Please select a smaller value.")

Output:

You might also like