Anda di halaman 1dari 3

DEPARTMENT OF COMPUTER ENGINEERING

Semester

S.E. Semester IV Computer Engineering

Subject

Analysis of Algorithms

Lectures
charge

Professor

In-

Practicals
Charge

Professor

In-

Laboratory number
Student Name

Prof. Sanjeev Dwivedi


Prof. Ashwin Ganesan
L07D

Sakharam S. Gawade

Roll Number

14102C2015

Grade

Subject Teachers
Signature

Experiment
Number

09

Experiment
Title

NQueen Problem

Resources
Apparatus
Used

Computer, Code::Blocks(IDE)

Objectives
Backtracking approach
(Skill
Set/
Knowledge
tested/imparte
d)

Description of the experiment:


The N Queen is the problem of placing N chess queens on an NN
chessboard so that no two queens attack each other. For example, following
is a solution for 4 Queen . Backtracking is similar to the brute force approach

where it tries all of the solutions but the only difference is that it
eliminates/avoids the partial candidate solutions as soon as it finds that that
path cannot lead to a solution.
We can divide this problem into a sub problem of placing single queen on the
chess board. To identify if this leads to a solution, we can check and see
does any of the already placed queens attack this position. If yes, then go to
next column. If no, then place this queen and move on to next queen

Program:
//nQueen Problem
#include<stdio.h>
int x[6]={0,0,0,0,0,0};
int place(int k,int i)
{
int j,mod;
for(j=1;j<=k-1;j++)
{
mod=x[j]-i;
if(mod<0)
{
mod=mod*-1;
}
if((x[j]==i) || (mod==(k-j)))
{
return 0;
}
}
return 1;
}
void nqueen(int k)
{
int i,j;
for(i=1;i<=5;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==5)
{
for(j=1;j<=5;j++)
{
printf("%d ",x[j]);
}
printf("\n");
}
else

{
nqueen(k+1);
}
}
}
}
int main()
{
printf("no of queens: 5\n");
nqueen(1);
return 1;
}

Output run:

Conclusions:
The complexity of nQueen problem is T(n) = n*T(n-1) + O(n 2) which
translates to O(N!) time complexity in average.

Anda mungkin juga menyukai