N-Queen problem in C.

 

01 #include<stdio.h>
02 #include<math.h>
03 int board[30],count=0;
04 void queen(int);
05 int placeQueen(int);
06 void printSolution(int);
07
08 int main()
09 {
10 int i,n;
11 printf("Queens Implementationn");
12 printf("Enter the number of Queensn");
13 scanf("%d",&n);
14 queen(n);
15 printf("nTotal solutions = %d",count);
16 return 0;
17 }
18
19 int placeQueen(int pos)
20 {
21 int i;
22 for(i=1; i<pos; i++)
23 {
24 if((board[i]==board[pos])||((abs(board[i]-board[pos])==abs(i-pos))))
25 return 0;
26 }
27 return 1;
28 }
29
30 void printSolution(int n)
31 {
32 int i,j;
33 count++;
34 printf("nnSolution [ %d ] :n",count);
35 for(i=1; i<=n; i++)
36 {
37 for(j=1; j<=n; j++)
38 {
39 if(board[i]==j)
40 printf("Qt");
41 else
42 printf("*t");
43 }
44 printf("n");
45 }
46 }
47 void queen(int n)
48 {
49 int k=1;
50 board[k]=0;
51 while(k!=0)
52 {
53 board[k]=board[k]+1;
54 while((board[k]<=n)&&!placeQueen(k))
55 board[k]++;
56 if(board[k]<=n)
57 {
58 if(k==n)
59 printSolution(n);
60 else
61 {
62 k++;
63 board[k]=0;
64 }
65 }
66 else
67 k--;
68 }
69 }
 
 OUTPUT :

Queens Implementation
Enter the number of Queens
4


Solution [ 1 ] :
* Q * *
* * * Q
Q * * *
* * Q *


Solution [ 2 ] :
* * Q *
Q * * *
* * * Q
* Q * *

Total solutions = 2

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *