The document presents a Python implementation of the N-Queens problem, which includes functions to check if a position is safe for placing a queen and to solve the problem using backtracking. It prompts the user to input the number of queens and attempts to print a valid board configuration. If no solution exists, it outputs a message indicating that there is no solution.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
10 views1 page
Exp 8 AOA Code
The document presents a Python implementation of the N-Queens problem, which includes functions to check if a position is safe for placing a queen and to solve the problem using backtracking. It prompts the user to input the number of queens and attempts to print a valid board configuration. If no solution exists, it outputs a message indicating that there is no solution.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1
Name Shyamdin prajapatri
Roll No 55
def is_safe(board, row, col, n):
for i in range(row): if board[i] == col or \ board[i] - i == col - row or \ board[i] + i == col + row: return False return True def solve_n_queens(n): def backtrack(row, board): if row == n: print_board(board, n) return True for col in range(n): if is_safe(board, row, col, n): board[row] = col if backtrack(row + 1, board): return True return False def print_board(board, n): for row in range(n): for col in range(n): if (row + col) % 2 == 0: print("Q" if board[row] == col else ".", end=" ") else: print("Q" if board[row] == col else ".", end=" ") print() board = [-1] * n if not backtrack(0, board): print("No solu on") try: n = int(input("Enter the number of queens: ")) solve_n_queens(n) except ValueError: print("Please enter a valid integer for the number of queens.")