Merge pull request #209 from jerryderry/backtracking-python

backtracking 8 queens problem in python
This commit is contained in:
wangzheng0822 2018-12-25 14:41:36 +08:00 committed by GitHub
commit 2a6ae2fe90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,25 @@
"""
Author: Wenru Dong
"""
from typing import List
def eight_queens() -> None:
solutions = []
def backtracking(queens_at_column: List[int], index_sums: List[int], index_diffs: List[int]) -> None:
row = len(queens_at_column)
if row == 8:
solutions.append(queens_at_column)
return
for col in range(8):
if col in queens_at_column or row + col in index_sums or row - col in index_diffs: continue
backtracking(queens_at_column + [col], index_sums + [row + col], index_diffs + [row - col])
backtracking([], [], [])
print(*(" " + " ".join("*" * i + "Q" + "*" * (8 - i - 1) + "\n" for i in solution) for solution in solutions), sep="\n")
if __name__ == "__main__":
eight_queens()