Solving N Queens Problem Using Backtracking
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.
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
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
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)
OBSERVTION:
THE NUMBER OF SOLUTION AND TIME TAKEN TO EXECUTE N
QUEENS PROBLEM
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.