8 Queens Puzzle++

2016-04-05, Comments

Yesterday I wrote about a Python solution to the 8 Queens puzzle.

n = 8
sqs = range(n)

Qs = (Q for Q in itertools.permutations(sqs)
      if n == len({Q[i]+i for i in sqs})
           == len({Q[i]-i for i in sqs}))

It’s possible to reproduce this strategy in C++:

The std::next_permutation algorithm stands alone in the C++ standard library. Used here, it pairs well with the similarly uncommon do ... while loop. The solution depends on the vector sqs starting off in sorted order, and by the end of the loop the vector will have been returned to this state.