forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
backtracking 8 queens problem in python
- Loading branch information
1 parent
2280169
commit 04158f2
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |