[This page is auto-generated; please prefer to read the article’s PDF Form.]
A trivial method is to generate all the 8! permutations of ℤ8 (using some permutation generation algorithm) and for each permutation check whether it satisfies the constraint C.
But a simple observation can help us optimize. Any permutation of m integers from ℤ8 (m < 8) is actually a prefix of some complete permutations of the 8 integers. Let us refer any such permutation as “permutation-prefix”. If a permutation-prefix does not satisfy constraint C for its m elements, then any permutation of the 8 integers starting with this permutation-prefix will not satisfy the constraint too; there are (8 −m)! such permutations. It means, we will not need to check these (8 −m)! permutations individually, and can reject them as a whole.
To utilize this observation, we will generate permutations in such a way that all permutations starting with a common permutation-prefix (of any length) get generated together as a separable subtask. So, if a permutation-prefix is found to violate the constraint, we can easily skip the generation (and checking) of all permutations sharing this prefix.
One such way of generating permutations has been shown below (for integers in ℤ8), implemented in C. It need not be an efficient permutation generation algorithm, but is simple to understand. permute(s) is supposed to generate all permutations of the integers not already placed till index (s − 1), over indices s to N − 1. print() prints the complete permutation from array a.
We will now modify this permutation generation method to solve the 8-Queens Problem. As mentioned earlier, if a permutation-prefix violates the constraint, we will skip generating (and checking) all permutations sharing this prefix. This skipping becomes easy here because all such permutations would get generated under a single recursive call permute(s + 1).
To record the (r − ar) and (r + ar) values already taken by the current permutation-prefix, we will use two boolean arrays. The modified method is shown below with all added lines marked using /* 8Q */. Method init() should be called first for doing initializations.
For placing element at index s, this permutation generation algorithm searches for an element which is not already placed till index (s− 1). We will now see a more efficient algorithm to generate permutations.
Copyright © 2021 Nitin Verma. All rights reserved.