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

Solving N Queens Problem Using Backtracking

The document discusses solving the N queens problem using a backtracking algorithm. It begins with an introduction to backtracking as a general algorithm for constraint satisfaction problems. It then describes how backtracking can be applied specifically to the N queens problem by placing queens one by one on a board, checking for clashes, and backtracking if no valid placement is found. Pseudocode is provided for the backtracking algorithm. It finds all solutions for board sizes from 4 to 14 queens and records the number of solutions and time taken. The advantages of backtracking for this problem are its ability to find all solutions efficiently. Disadvantages include slower speed for large branching factors and high space complexity due to recursion.

Uploaded by

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

Solving N Queens Problem Using Backtracking

The document discusses solving the N queens problem using a backtracking algorithm. It begins with an introduction to backtracking as a general algorithm for constraint satisfaction problems. It then describes how backtracking can be applied specifically to the N queens problem by placing queens one by one on a board, checking for clashes, and backtracking if no valid placement is found. Pseudocode is provided for the backtracking algorithm. It finds all solutions for board sizes from 4 to 14 queens and records the number of solutions and time taken. The advantages of backtracking for this problem are its ability to find all solutions efficiently. Disadvantages include slower speed for large branching factors and high space complexity due to recursion.

Uploaded by

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

SOLVING N QUEENS PROBLEM USING BACKTRACKING

INTRODUCTION

Backtracking is a general algorithm for finding all (or some) solutions to some computational
problems, notably constraint satisfaction problems, that incrementally builds candidates to the
solutions, and abandons a candidate ("backtracks") as soon as it determines that the candidate
cannot possibly be completed to a valid solution.

Backtracking is finding the solution of a problem whereby the solution depends on the
previous steps taken. For example, in a maze problem, the solution depends on all the steps
you take one-by-one. If any of those steps is wrong, then it will not lead us to the solution. In
a maze problem, we first choose a path and continue moving along it. But once we
understand that the particular path is incorrect, then we just come back and change it. This is
what backtracking basically is.

Thus, the general steps of backtracking are:

 start with a sub-solution


 check if this sub-solution will lead to the solution or not
 If not, then come back and change the sub-solution and continue again

SOLVING N QUEENS PROBLEM USING BACKTRACKING

The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this row
and column as part of the solution. If we do not find such a row due to clashes then we
backtrack and return false.

ALGORITHM

 Start in the leftmost column


 If all queens are placed
return true
 Try all rows in the current column. Do following for every tried row.
a) If the queen can be placed safely in this row then mark this [row, column]
as part of the solution and recursively check if placing queen here leads to a
solution.
b) If placing the queen in [row, column] leads to a solution then return
true.
c) If placing queen doesn't lead to a solution then unmark this [row, column]
(Backtrack) and go to step (a) to try other rows.
 If all rows have been tried and nothing worked, return false to trigger backtracking.

CODE FOR FINDING THE NUMBER OF SOLUIONS FOR N


QUEEN PROBLEM USING BACKTARCKING IN PYTHON

import copy
import time
# a function that helps to to get the right input size
#op:size of the board
def take_input():
"""Accepts the size of the chess board"""

while True:
try:
size = int(input('What is the size of the chessboard? n = '))
if size == 1:
print("Trivial solution, choose a board size of atleast 4")
if size <= 3:
print("Enter a value such that size>=4")
continue
return size
except ValueError:#invalid value
print("Invalid value entered. Enter again")
#create a board
#ip:size of the board
#returns a board of n*n
def get_board(size):
"""Returns an n by n board"""
board = [0]*size
for ix in range(size):
board[ix] = [0]*size
return board
#helper function to solve for solve
#ip:board ,row and col u want to check is safe or no
#op:true or fase depending on func
def is_safe(board, row, col, size):
"""Check if it's safe to place a queen at board[x][y]"""
#since there is no queen to the right of the one we are trying to place
#check row on left side
for iy in range(col):
if board[row][iy] == 1:
return False
#diagonallly above to the left
ix, iy = row, col
while ix >= 0 and iy >= 0:
if board[ix][iy] == 1:
return False
ix-=1
iy-=1
#diagonally below to the left
jx, jy = row,col
while jx < size and jy >= 0:
if board[jx][jy] == 1:
return False
jx+=1
jy-=1

return True
#solve for column one by one

def solve(board, col, size):


"""Use backtracking to find all solutions"""
#base case
if col >= size:
return

for i in range(size):
if is_safe(board, i, col, size):#each row in a particular column
board[i][col] = 1#put the queen there
if col == size-1:# solution
add_solution(board)#add solution to the board
board[i][col] = 0#backtrack
return
solve(board, col+1, size)
#backtrack
board[i][col] = 0
#storing the solution to the solution array
def add_solution(board):
"""Saves the board state to the global variable 'solutions'"""
global solutions
saved_board = copy.deepcopy(board)
solutions.append(saved_board)

size = take_input()#get the size of the board


board = get_board(size)#get a board of size n*n
solutions = [] #to keep a copy of solutions
start=time.time()
solve(board, 0, size)
end=time.time()
print("Total solutions = {}".format(len(solutions)))
print("time ",end-start)
for s in range(len(solutions)):
print(solutions[s])
OUTPUT

OBSERVTION:
THE NUMBER OF SOLUTION AND TIME TAKEN TO EXECUTE N
QUEENS PROBLEM

Size 4 Total solutions = 2 time 0.0005376338958740234 seconds


Size 5 Total solutions = 10 time 0.0012020339965820312 seconds
Size 6 Total solutions = 4 time 0.001993894577026367 seconds
Size 7 Total solutions = 40 time 0.010971784591674805 seconds
Size 8 Total solutions = 92 time 0.031912803649902344 seconds
Size 9 Total solutions = 352 time 0.13569879531860352 seconds
Size 10 Total solutions = 724 time 1.022794246673584 seconds
Size 11 Total solutions = 2680 time 5.528423070907593 seconds
Size 12 Total solutions = 14200 time 29.549843072891235 seconds
Size 13 Total solutions = 73712 time 159.312264919281 seconds
Size 14 Total solutions = 365596 time 814.2662787437439 seconds

ADVANTAGES OVER OTHER METHODS:

The major advantage of the backtracking algorithm is the ability to find and count all
the possible solutions rather than just one while offering decent speed. In fact this is
the reason it is so widely used. Also one can easily produce a parallel version of the
backtracking algorithm increasing speed several times just by starting multiple threads
with different starting positions of the first queens.
DISADVANTAGES
o backtracking is slow
o Very time inefficient in lot of cases when branching factor is large
o Large space complexity because we are using recursion

CONCLUSION

 Using the concept of backtracking the major advantage was the ability to find
and count the possible solutions rather than just one while offering decent
speed.
 Finding it’s applications in branches like Artificial Intelligence, it can be
viewed as a very critical method to generate optimum solutions.

You might also like