r/programmingchallenges • • Jul 16 '12
N-Queens: C++
Looking for some help with the N-Queens puzzle. I have a recursive solution that works reasonably well for N <= 10, but it's not fast enough (Solve for N = 13 in < 5 seconds) I need to produce all possible combinations and print the queen positions in a certain way. I need a different algorithm than what I have at the moment, any help? I know that I can eliminate quite a lot of board positions by looking at reflections and rotations, but I do not know how to do this. Any Help?
6
Upvotes
View all comments
Show parent comment
3
u/Cosmologicon Jul 17 '12
Algorithm X is just one optimization on top of that. It chooses which row to put a queen on next in a more optimal order. Basically, you pick the row (or column) that has the fewest remaining squares available. If there's any row or column without a queen that has 0 squares available, you don't have any solutions along this branch and you backtrack.
There's a little more bookkeeping involved so you're not constantly recomputing how many squares each row and column has open, but that's the basic idea.