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

N-Queens Problem - Python Backtracking Solution Explained

Ai

Uploaded by

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

N-Queens Problem - Python Backtracking Solution Explained

Ai

Uploaded by

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

Backtracking Explained in Layman’s Terms

Backtracking is a problem-solving algorithm that builds a solution incrementally and


abandons a solution (or "backtracks") as soon as it determines that the solution
cannot lead to a valid result. It is commonly used in scenarios where you are
searching through a solution space, like puzzles, combinatorial problems, or decision
trees.

How Backtracking Works:


Imagine you are trying to solve a maze. You start at the entrance and walk down a
path. If you hit a dead end, you backtrack to the last decision point (where you could
have chosen a different path), and try another path. You repeat this process until you
either find the exit or determine that there is no solution.

Key Steps in Backtracking:


1. Choose a starting point: Start exploring the solution space.
2. Try a possible option: Take one step or make one decision.
3. Check if the current step leads to a valid solution:
If yes, continue exploring from this point.
If no, backtrack to the previous step and try another option.

4. Repeat the above process until all options are explored or a solution is found.

Backtracking is essentially a refined brute-force method that prunes solutions that


are unlikely to lead to a solution, making the search more efficient.

Example: Solving the N-Queens Problem


Let’s use the classic N-Queens problem as an example to understand backtracking. The
goal of the N-Queens problem is to place N queens on an N × N chessboard such that
no two queens threaten each other. In other words, no two queens can be placed in the
same row, column, or diagonal.

Steps to Solve Using Backtracking:


1. Start with the first column and attempt to place a queen in a row.
2. Check if placing the queen is valid (i.e., it’s not threatened by any other
queen).
3. If it’s valid, move to the next column and repeat the process.
4. If it’s not valid, backtrack and try the next available row.
5. Continue this process until all queens are placed, or backtrack completely if
no solution is found.

Python Example: N-Queens Solution Using Backtracking

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


# Check the row on the left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on the left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check lower diagonal on the left side


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

return True

def solve_nqueens_util(board, col, n):


# Base case: All queens are placed
if col >= n:
return True

# Try placing this queen in all rows one by one


for i in range(n):
if is_safe(board, i, col, n):
# Place this queen on board
board[i][col] = 1

# Recur to place the rest of the queens


if solve_nqueens_util(board, col + 1, n):
return True

# If placing queen doesn't lead to a solution, backtrack


board[i][col] = 0

return False

def solve_nqueens(n):
# Initialize the board
board = [[0 for _ in range(n)] for _ in range(n)]

if not solve_nqueens_util(board, 0, n):


print("No solution exists")
return

# Print the solution board


for row in board:
print(" ".join(str(x) for x in row))

# Example for 4-Queens problem


solve_nqueens(4)

You might also like