import random def is_valid(board, row, col): for i in range(8): if board[i][col] or board[row][i]: return False if (row + i < 8 and col + i < 8 and board[row + i][col + i]) or \ (row - i >= 0 and col - i >= 0 and board[row - i][col - i]) or \ (row + i < 8 and col - i >= 0 and board[row + i][col - i]) or \ (row - i >= 0 and col + i < 8 and board[row - i][col + i]): return False return True def solutions_generator(board, row): if row == 8: yield [row.copy() for row in board] return for col in range(8): if is_valid(board, row, col): board[row][col] = 1 yield from solutions_generator(board, row + 1) board[row][col] = 0 def solve(): board = [[0] * 8 for _ in range(8)] yield from solutions_generator(board, 0) for solution in solve(): for row in solution: print(row) print("--------") input("Press Enter for the next solution...")