You are on page 1of 3

22103091

Week-5
Program 8: Program to find the solution to the N queen’s problem using backtracking.
Description:
This problem is to find an arrangement of N queens on a chess board, such that no queen can
attack any other queens on the board.
The chess queens can attack in any direction as horizontal, vertical, horizontal and diagonal
way.
A binary matrix is used to display the positions of N Queens, where no queens can attack
other queens.

ALGORITHM:
• isValid(board, row, col):
Begin
if there is a queen at the left of current col, then
return false
if there is a queen at the left upper diagonal, then
return false
if there is a queen at the left lower diagonal, then
return false;
return true //otherwise it is valid place
End

• solveNQueen(board, col):
Begin
if all columns are filled, then
return true
for each row of the board, do
if isValid(board, i, col), then
set queen at place (i, col) in the board
if solveNQueen(board, col+1) = true, then
return true
otherwise remove queen from place (i, col) from board.
done
return false
End

Time Complexity:
Time Complexity - O(N!):
For the first row, we check N columns; for the second row, we check the N - 1 column and so
on. Hence, the time complexity will be N * (N-1) * (N-2) …. i.e. O(N!)
Space Complexity - O(N^2):
O(N^2), where ‘N’ is the number of queens.

35
22103091

SOURCE CODE:
#include<bits/stdc++.h>
using namespace std;

bool isSafe(vector<vector<int>> &board,int col,int row){


int i,j;
for(i=row;i>=0;i--){
if(board[i][col]==1)return false;
}
for(i=row,j=col;i>=0 && j>=0 ;i--,j-- ){
if(board[i][j]==1)return false;
}
for(i=row,j=col;i>=0 && j< board.size();i--,j++){
if(board[i][j]==1)return false;
}
return true;
}
bool NQueen(vector<vector<int>> &board,int row){
int n=board.size();
if(row>=n)return true;
for(int i=0;i<n;i++){
if(isSafe(board,i,row)==true){
board[row][i]=1;
if(NQueen(board,row+1)==true){
return true;
}
board[row][i]=0;
}
}
return false;
}
int main(){
int n ;
cout<<"Enter the size of board: ";
cin>>n;
vector<vector<int>>board(n,vector<int>(n,0));
if(NQueen(board,0)==false){
cout<<"Solution not possible"<<endl;
}else{
cout<<"Solution Board is:"<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
36
22103091

OUTPUT:

37

You might also like