- N queens puzzle
-
Sample program
The following is a C Coded by "Tamajit Chakraborty" It can finds one solution to the N queens problem.
#include<stdio.h> #include<conio.h> #define insertQ 1 #define full 0 #define cons 5 void main() { int n,i,j,a[100][100],k,x=0,c; clrscr(); printf("Enter The Number of QUEENS: "); scanf("%d",&n); do { c=n; for(i=0;i<n;i++) for(j=0;j<n;j++) a[i][j]=cons; a[0][x]=insertQ; c--; if(x>0) { a[1][x-1]=full; for(j=x-1;j>=0;j--) a[0][j]=full; } for(i=1;i<n;i++) a[i][x]=full; a[1][x+1]=full; for(j=x+1;j<n;j++) a[0][j]=full; for(i=1;i<n;i++) { for(j=0;j<n;j++) { if(a[i][j]==cons) { a[i][j]=insertQ; c--; for(k=1;i+k<n;k++) a[i+k][j]=full; for(k=1;j+k<n;k++) a[i][j+k]=full; if(j>0) a[i+1][j-1]=full; if(i+1<n && j+1<n) a[i+1][j+1]=full; } } } x++; }while(c!=0); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(a[i][j]!=full) printf("Q "); else printf("X "); } printf("\n"); } getch(); }
Wikimedia Foundation. 2010.