0% found this document useful (0 votes)
6 views4 pages

005 AI Program 10

The document describes a Python program that solves the 8-Queens problem using a backtracking algorithm. It includes functions for checking safe placements of queens, printing the board configuration, and recursively placing queens on an 8x8 chessboard. The program aims to find and print all valid configurations where no two queens threaten each other.

Uploaded by

latanowpada
Copyright
© © All Rights Reserved
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% found this document useful (0 votes)
6 views4 pages

005 AI Program 10

The document describes a Python program that solves the 8-Queens problem using a backtracking algorithm. It includes functions for checking safe placements of queens, printing the board configuration, and recursively placing queens on an 8x8 chessboard. The program aims to find and print all valid configurations where no two queens threaten each other.

Uploaded by

latanowpada
Copyright
© © All Rights Reserved
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/ 4

Write a python program to 8-Queens Problem Problem

N = 8 # Size of the board


def print_solution(board):
"""Prints the chessboard configuration."""
for row in board:
print(" ".join("Q" if col else "." for col in row))
print("\n")
def is_safe(board, row, col):
"""Checks if it's safe to place a queen at board[row][col]."""
# Check column
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 # Safe placement
def solve_n_queens(board, row):
"""Solves the N-Queens problem using backtracking."""
if row == N:
print_solution(board) # Print valid board configuration
return True # Solution found
for col in range(N): # Try placing queen in each column
if is_safe(board, row, col):
board[row][col] = 1 # Place the queen
if solve_n_queens(board, row + 1):
return True
board[row][col] = 0 # Backtrack if not a solution

return False # No valid placement found

# Initialize an 8×8 chessboard (0 represents empty, 1 represents a queen)


chess_board = [[0] * N for _ in range(N)]
solve_n_queens(chess_board, 0)
🧩 Problem:
Place 8 queens on an 8×8 chessboard such that no two queens threaten each other. This means:
 No two queens can be in the same row, column, or diagonal.

🧩 Code Breakdown:
✅ Step 1: Define the board
N = 8
chess_board = [[0] * N for _ in range(N)]
 Creates an 8x8 board filled with zeros.
 0 means empty square, 1 means a queen is placed there.

✅ Step 2: The print_solution function


def print_solution(board):
...
 When a complete valid solution is found, it prints the board using:
o Q for queen (1)
o . for empty (0)

✅ Step 3: The is_safe function


def is_safe(board, row, col):
 Checks if placing a queen at position (row, col) is safe:
o Column check: no other queen above in the same column.
o Upper-left diagonal check
o Upper-right diagonal check

✅ Step 4: The solve_n_queens function (Backtracking)


def solve_n_queens(board, row):
 Recursive function: places queens row by row.
 Base case: if row == N, all 8 queens are placed → print the solution.
 Recursive case:
o Try placing the queen in each column of the current row.
o If safe:
 Place queen (board[row][col] = 1)
 Call solve_n_queens for the next row.
 If that doesn't work, backtrack (remove queen).

🧩 Step-by-Step Trace of Execution


Let’s simulate the first few steps:
🔁 Start: solve_n_queens(chess_board, 0)
Try to place a queen in row 0:
 Try col = 0 → is_safe(0, 0) → ✅ safe → place queen.
 Board now: queen at (0, 0)
🔁 Recurse: solve_n_queens(board, 1)
Try to place queen in row 1:
 col = 0 → is_safe(1, 0) → ❌(same column)
 col = 1 → is_safe(1, 1) → ❌(diagonal)
 col = 2 → is_safe(1, 2) → ✅→ place queen.
 Board: queens at (0, 0), (1, 2)
🔁 Recurse: solve_n_queens(board, 2)
Place queen in row 2:
 col = 0 → ❌
 col = 1 → ❌
 col = 2 → ❌
 col = 3 → ✅→ place queen.
...
🔁 Keep Recursing Until:
Eventually, either:
 All 8 queens are placed → ✅ print_solution()
 Or no valid column in a row → ❌ → backtrack (remove queen) and try next option.

🧩 Backtracking In Action:
If a configuration fails later (e.g., row 4 has no valid positions), the code:
 Removes the last placed queen (board[row][col] = 0)
 Tries the next possible column in the previous row.
This continues until a full solution is found or all combinations are tried.

🧩 Output:
The first valid 8-queen configuration is printed like this:
Q . . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . . . Q . .
. . Q . . . . .
. . . . . . Q .
. Q . . . . . .
. . . Q . . . .

You might also like