sandipan

C code to solve the N-queens problem

Sep 6th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. /*NQUEEN PROBLEM*/
  2. #include<stdio.h>
  3. #include<conio.h>
  4. #include<stdlib.h>
  5.  
  6. int a[100][100],n,*p[100];
  7. void prohibit(int,int);
  8. void notprohibit(int,int);
  9.  
  10. void main() {
  11.    
  12.     int f=0,c,i,j,t=0,b[100];
  13.     printf("\nEnter the number of Queens\n");
  14.     scanf("%d",&n);
  15.     if(n==2 || n==3) {
  16.         printf("\nNull pointer assignment--->No Solutions!!!\n");getch();exit(0);  
  17.     }
  18.     for(c=0;c<n;++c) {
  19.         int *r;
  20.         if(!f)
  21.         p[c]=(*(a+c)+0);
  22.         for(r=p[c];r<=&a[c][n-1] && *r==1;++r);
  23.         if(r<=&a[c][n-1]) {
  24.             a[c][r-(*(a+c)+0)]=2;
  25.             prohibit(c,r-(*(a+c)+0));
  26.             p[c]=++r;
  27.             f=0;
  28.         }
  29.         else {
  30.             --c;
  31.             a[c][(p[c]-(*(a+c)+0))-1]=0;
  32.             notprohibit(c,(p[c]-(*(a+c)+0))-1);
  33.             f=1;
  34.             --c;
  35.         }
  36.     }
  37.     for(i=0;i<n;++i) {
  38.         for(j=0;j<n;++j) {
  39.             if(a[i][j]==2)  {
  40.                 printf(" Q ");
  41.                 b[t]=j;
  42.                 ++t;
  43.             }
  44.             else
  45.                 printf(" * ");
  46.         }
  47.         printf("\n");
  48.     }
  49.     printf("\n\n");
  50.     printf("\nThe Position(s) are=");
  51.     for(t=0;t<n;++t)
  52.         printf(" %d",b[t]);
  53.     getch();
  54. }
  55. void prohibit(int i,int j) {
  56.     int k,l,m;
  57.     for(k=i+1,l=j+1,m=j-1;k<n;++k,++l,--m) {
  58.         a[k][j]=1;
  59.         if(l<n)
  60.             a[k][l]=1;
  61.         if(m>=0)
  62.             a[k][m]=1;
  63.     }
  64. }
  65. void notprohibit(int i,int j) {
  66.     int k,e,l,m;
  67.     for(k=i+1,l=j+1,m=j-1;k<n;++k,++l,--m)  {
  68.         a[k][j]=0;
  69.         if(l<n)
  70.             a[k][l]=0;
  71.         if(m>=0)
  72.             a[k][m]=0;
  73.     }
  74.     for(e=0;e<i;++e)
  75.         prohibit(e,(p[e]-(*(a+e)+0))-1);
  76. }
Add Comment
Please, Sign In to add comment