All possible solution of the n-Queen's algorithm

前端 未结 1 2030
萌比男神i
萌比男神i 2020-12-19 08:49

When implementing an algorithm for all possible solution of an n-Queen problem, i found that the same solution is reached by many branches. Is there any good way to generate

1条回答
  •  情歌与酒
    2020-12-19 09:25

    You should make use of the fact that each queen must be placed in a different column. If you have placed already k queens in the first k columns, recursively place queen number k+1 in column k+1 and go through rows 1 to n (and not through all n*n cells, as you algo currently does). Continue with k:=k+1 for each valid placement. That will avoid any duplicate results, since this algo does not generate any duplicate boards at all.

    EDIT: to your question about avoiding of symmetries: a part of those can be avoided beforehand, for example, by restricting queen 1 in column 1 to rows 1,...n/2. If you want to avoid the output of symmetric solutions completely, you will have to store every found solution in a list and whenever you find a new solution, before printing it out, test if one of it's symmetric equivalents is already there in the list.

    To make this more efficient, you can work with a "canoncial representation" of each board, defined as follows. Generate all symmetric boards of a given one, pack each one of it into a byte array, and among those arrays keep the array which, interpreted as a big number, has the minimum value. This packed represention is a unique identifier of the symmetry class of each board and can be easily put in a dictionary / hash table, which makes testing if that symmetry class already appeared very efficient.

    0 讨论(0)
提交回复
热议问题