N-queens problem: Difference between revisions

m
Line 12,829:
 
===Python: Simple Backtracking Solution (Niklaus Wirth Algorithm)===
The following program is a translation of Niklaus Wirth's solution into the Python programming language, but does without the index arithmetic used in the original and uses simple lists instead, which means that the array ''x'' for recording the solution can be omitted. A generator replaces the procedure (see [https://www.inf.ethz.ch/personal/wirth/AD Niklaus Wirth] or [https://informatika-21.pdfru/ADen/ Fyodor Tkachov]: Algorithms and Data Structures], pages 114 to 118). On a regular 8x8 board only 15,720 possible queen positions are examined.
<syntaxhighlight lang="python">def queens(n: int, i: int, a: list, b: list, c: list):
if i < n:
Line 12,842:
print(solution)</syntaxhighlight>
The algorithm can be slightly improved by using sets instead of lists (cf. backtracking on permutations). 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. However, since these two solutions are intended for educational purposes, they are neither resource-friendly nor optimized for speed. The next program (backtracking on permutations) shows a much faster solution that also uses less space on the stack.
<syntaxhighlight lang="python">def queens(x: list, 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(x + [j], 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>
 
305

edits