You must use the fact that each queen must be placed in a different column. If you have already placed k kings in the first k columns, recursively put the number of kings k + 1 in column k + 1 and go through lines 1 to n (and not through all n * n cells, as you currently do). Continue with k: = k + 1 for each valid allocation. This will avoid any duplicate results, since this algorithm does not generate duplicate boards at all.
EDIT: to your question about the exclusion of symmetry: some of them can be avoided in advance, for example, by restricting Queen 1 in column 1 to rows 1, ... n/2
. If you want to completely exclude the output of symmetric solutions, you will need to store each solution found in the list and whenever you find a new solution, check whether there is one of its symmetric equivalents in the list before printing it.
To make this more efficient, you can work with the “canonical representation” of each board, defined as follows. Generate all the symmetric boards of the given one, pack each of them into an array of bytes, and among these arrays, an array that is interpreted as a large number is stored has a minimum value. This packaged view is a unique identifier for the symmetry class of each board and can easily be placed in the dictionary / hash table, which makes testing if this symmetry class has already been very effective.
source share