N-queens problem: Difference between revisions

m
→‎Python: Backtracking on permutations: Restored the original look
m (→‎Python: Backtracking on permutations: Restored the original look)
 
Line 12,865:
<syntaxhighlight lang="python">def queens(n: int):
 
def queensub(i: int):
if i < n:
for k in range(i, n):
h, j = a[i], a[k]
if b[i + j] and c[i - j]:
a[i], a[k] = ja[k], ha[i]
b[i + j] = c[i - j] = False
yield from queensub(i + 1)
b[i + j] = c[i - j] = True
a[i], a[k] = ha[k], ja[i]
else:
yield a
Line 12,881:
b = [True] * (2 * n - 1)
c = [True] * (2 * n - 1)
yield from queensub(0)
 
 
Line 12,893:
<syntaxhighlight lang="python">def queens_lex(n: int):
 
def queensub(i: int):
if i < n:
for k in range(i, n):
h, j = a[i], a[k]
a[i], a[k] = ja[k], ha[i]
if b[i + j] and c[i - j]:
b[i + j] = c[i - j] = False
yield from queensub(i + 1)
b[i + j] = c[i - j] = True
a[i:(n - 1)], a[n - 1] = a[(i + 1):n], a[i]
Line 12,909:
b = [True] * (2 * n - 1)
c = [True] * (2 * n - 1)
yield from queensub(0)
 
 
305

edits