Jump to content

N-queens problem: Difference between revisions

m
→‎Python: Niklaus Wirth algorithm: Removed redundant (duplicate) example.
m (→‎Python: Niklaus Wirth algorithm: Added a more optimized version.)
m (→‎Python: Niklaus Wirth algorithm: Removed redundant (duplicate) example.)
Line 12,841:
for solution in queens(8, 0, [], [], []):
print(solution)</syntaxhighlight>
The algorithm can be slightlyeasily improved by using sets instead of lists. Butand thisavoiding makestime- theand algorithmspace-consuming aimplicit bitcopy harder to read, since the list x has to be added to record the solutionoperations. 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):
305

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.