Write a C ++ program : Eight queens are to be placed on an 8 x 8 chessboard in s
ID: 3533326 • Letter: W
Question
Write a C ++ program : Eight queens are to be placed on an 8 x 8 chessboard in such a way that one queen is to be in each row. A program will store an array x[] with capacity 8 to represent such a configuration. If x[r] has value c then in row r there is a queen in column c. Write a program that asks a user to enter the columns that contain queens in the 8 rows. The program then prints the board. For example, if the user enters: 0,3,4,0,0,7,6,7 the program should print:
Q.......
...Q....
....Q...
Q.......
Q.......
.......Q
......Q.
.......Q
(Hint: Use nested for loop, if column c == array[r] Print
Explanation / Answer
#include<stdio.h>
#include<conio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
int i;
for(i=1;i<pos;i++)
{
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf(" Solution #%d: ",count);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i]==j)
printf("Q ");
else
printf("* ");
}
printf(" ");
}
}
void queen(int n)
{
int k=1;
a[k]=0;
while(k!=0)
{
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n)
{
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
}
}
else
k--;
}
}
void main()
{
int i,n;
clrscr();
printf("Enter the number of Queens ");
scanf("%d",&n);
queen(n);
printf(" Total solutions=%d",count);
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.