Posted By

zava on 08/19/10


Tagged

textmate bit eight queens arrary


Versions (?)

eight queens puzzle.c


 / Published in: C
 

  1. #include "stdio.h"
  2.  
  3. #define SIZE 8
  4.  
  5. void printrow(unsigned int q)
  6. {
  7. for (int i=0; i < SIZE; i++)
  8. {
  9. char c = (q >> i) & 1 ? '*' : '.';
  10. putchar(c);
  11. }
  12. putchar('n');
  13. }
  14.  
  15. extern void placeQ(int x, int y)
  16. {
  17. static unsigned int Q[SIZE];
  18. static unsigned int nSolutions;
  19.  
  20. unsigned int col0, col1, col2,q;
  21. col0 = 1 << (SIZE - 1 - x);
  22. for (int row = 0; row < y; row++)
  23. {
  24. col1 = col0 << (y - row);
  25. col2 = col0 >> (y - row);
  26. q = Q[row];
  27. if (q == col0 || q == col1 || q == col2) goto nextcolumn;
  28. }
  29.  
  30. Q[y] = col0;
  31. if (y == SIZE - 1) // finished
  32. {
  33. printf("nSolution #%d:n", ++nSolutions);
  34. for (int i = 0; i < SIZE; i++) printrow(Q[i]);
  35. }
  36. else
  37. {
  38. // continue to try next row
  39. placeQ(0, y + 1);
  40. }
  41. Q[y] = 0;
  42.  
  43. nextcolumn:
  44. if (x < SIZE - 1) placeQ(x + 1, y);
  45. }
  46.  
  47. int main (int argc, char const *argv[])
  48. {
  49. placeQ(0, 0);
  50. return 0;
  51. }

Report this snippet  

You need to login to post a comment.