milardovich

Trying to solve the n-queens problem

Mar 24th, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. /*
  2.  * N-queens problem
  3.  * Author: Sergio Milardovich
  4.  * This script is for academic-only usage
  5.  */
  6.  
  7. // Just some little tests... this script isn't done yet
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <stdbool.h>
  12.  
  13. int q[8];
  14.  
  15. bool place(int k, int i);
  16.  
  17. void printConfiguration(int q[8]);
  18.  
  19. void nQueens(int k, int n);
  20.  
  21. void main(){
  22.     nQueens(0,8);
  23. }
  24.  
  25. bool place(int k,int i){
  26.     int j;
  27.     for(j=0;j<(k-1);j++){
  28.         if((q[j] == i) || (abs(q[j]-i) == abs(j-k))){
  29.             return false;
  30.         }
  31.     }
  32.     return true;
  33. }
  34.  
  35. void nQueens(k,n){
  36.     int i;
  37.     printf("\n\n");
  38.     for(i=0;i<n;i++){
  39.         if(place(k,i) == true){
  40.             q[k] = i;
  41.             if(k == n){
  42.                 printConfiguration(q);
  43.             } else {
  44.                 nQueens(k+1,n);
  45.             }
  46.         }
  47.     }
  48. }
  49.  
  50. void printConfiguration(int q[8]){
  51.     int i,k;
  52.     for(k=0;k=8;k++){
  53.         for(i=0;i<8;i++){
  54.             if(q[k] == i)
  55.                 printf("1 ");
  56.             else
  57.                 printf("0 ");  
  58.         }
  59.         printf("\n");
  60.     }
  61.     printf("\n\n\n");
  62. }
Advertisement
Add Comment
Please, Sign In to add comment