/* Here's a *really* souped-up variant of the algorithm, which replaces the
   inner loop (looking for a good candidate) by a single instruction!
   The main trick is that (x & -x) finds the least-significant bit of x containing
   a 1, and returns a word with just that bit set.
   For example, if x = 0...0110100, then -x = 1...1001100, so (x & -x) = 0...0000100.
   Some additional tricks are used to simplify the code; for example,
   by keeping track of *good* rows (rather than bad ones), we can avoid
   keeping track of the current column altogether. 
  
   This code was written by Thomas Nordin, based on an original apparently written
   by Marcel van Kervinck.  All rights reserved by the authors.
*/

int solutions = 0;

void rqueens(unsigned int good_rows, 
	     unsigned int bad_up_diags, 
	     unsigned int bad_down_diags)
{
  unsigned int candidate = 0;
  unsigned int good = good_rows & ~bad_up_diags & ~bad_down_diags;
  
  if (good_rows)
    while (good ^= candidate, candidate = good & -good)
      rqueens(good_rows ^ candidate, 
	      (bad_up_diags | candidate) << 1, 
	      (bad_down_diags | candidate) >> 1);
  else solutions++;
}

int queens(int n) {
  solutions = 0;
  rqueens((1<<n) - 1, 0, 0);
  return solutions;
}


