Skip to content

Commit

Permalink
backtracking 8 queens problem in python
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryderry committed Dec 24, 2018
1 parent 2280169 commit 04158f2
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions python/39_backtracking/backtracking.py
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 04158f2

Please sign in to comment.