N queens problem

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Backtracking definition

Backtracking the solution of the problem depends on the previous


steps taken. We take a step and then analyse it that whether it will
give the correct answer or not? and if not, then we move back and
change the previous step.
And we using the recursive method to loop every steps till find a
way to place the queen here we taken the 8 queens to place in 8x8
chessboard using backtracking
Recursive Function:
Recursive function that solves the problem by placing queens on the
board, one by one. It first checks if all the queens are placed and
return True if yes, otherwise it loops through each position on the
board, checks if it is under attack, and if not, place a queen on that
position, then calls itself with n-1. If this call returns False, which
means it is not possible to place n-1 queens on the remaining board,
it unplaces the queen and backtracks to try the next position.
print ("Enter the number of queens")
N = int(input())
board = [[0]*N for _ in range(N)]
def attack(i, j):
#checking vertically and horizontally
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False

def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0

return False

N_queens(N)
for i in board:
print (i)
Start

Input enter
Dataflow: the number
of queen(N)

Initialization create
an empty
chessboard

Inner
Outer
Loop
Loop

Check placing
queen in
current
position is safe

yes no
yes If safe
placement
nt
Move to Backtracking
next column
Remove queen and
yes no place next column

All column All rows


tried tried

yes

Solution
found

End
Output:
Enter the number of queens
8
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]

You might also like