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 |
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): |
||