Otto regine

Wikipedia > Rompicapo delle otto regine

Soluzione 1

wiki.python.org > Simple Programs

L’esempio di codice n. 18 stampa tutte le soluzioni

BOARD_SIZE = 8
 
def under_attack(col, queens):
    left  = col
    right = col
    for r, c in reversed(queens):
        left  = left-1
        right = right+1
        if c in (left, col, right):
            return True
    return False
 
def solve(n):
    if(n == 0):
        return [[]]
    smaller_solutions = solve(n-1)
    return [solution+[(n, i+1)]
        for i in range(BOARD_SIZE)
            for solution in smaller_solutions
                if not under_attack(i+1, solution)]
 
for answer in solve(BOARD_SIZE):
    print(answer)

Soluzione 2

Wikipedia > Eight queens puzzle

def queens(n, i, a, b, c):
    if i < n:
        for j in range(n):
            if(j not in a) and (i+j not in b) and (i-j not in c):
                yield from queens(n, i+1, a+[j], b+[i+j], c+[i-j])
            else:
                yield a

for solution in queens(8, 0, [], [], []):
    print(solution)