N-queens problem: Difference between revisions

Content added Content deleted
m (→‎Python: Niklaus Wirth algorithm: Added a more optimized version.)
m (→‎Python: Niklaus Wirth algorithm: Removed redundant (duplicate) example.)
Line 12,841: Line 12,841:
for solution in queens(8, 0, [], [], []):
for solution in queens(8, 0, [], [], []):
print(solution)</syntaxhighlight>
print(solution)</syntaxhighlight>
The algorithm can be slightly improved by using sets instead of lists. But this makes the algorithm a bit harder to read, since the list x has to be added to record the solution. On a regular 8x8 board only 5,508 possible queen positions are examined.
The algorithm can be easily improved by using sets instead of lists and avoiding time- and space-consuming implicit copy operations. On a regular 8x8 board only 5,508 possible queen positions are examined.
<syntaxhighlight lang="python">def queens(i: int, a: set, b: set, c: set, x: list):
if a: # set a is not empty
for j in a:
if i + j not in b and i - j not in c:
yield from queens(i + 1, a - {j}, b | {i + j}, c | {i - j}, x + [j])
else:
yield x


for solution in queens(0, set(range(8)), set(), set(), []):
print(solution)</syntaxhighlight>
However, because these examples are intended for educational purposes, they are not optimized for resources or speed. The next example shows a more optimized solution that also requires less space on the stack.
<syntaxhighlight lang="python">def queens(n: int):
<syntaxhighlight lang="python">def queens(n: int):