Last active
May 6, 2022 14:42
-
-
Save ibeauregard/51ea083331b75af4cadc5f20d3f66dd6 to your computer and use it in GitHub Desktop.
The famous N-Queens problem. n_queens(n) returns all the ways in which n queens can be placed on a n x n chessboard so that none of the queens is attacked.
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
def n_queens(n): | |
def solve(): | |
i = len(columns) | |
if i == n: | |
solutions.append([f"{'.' * col}Q{'.' * (n - col - 1)}" for col in columns]) | |
return | |
for j in range(n): | |
if is_legal(i, j): | |
add_candidate(i, j) | |
solve() | |
remove_candidate(i, j) | |
def is_legal(i, j): | |
return not any([j in columns, i - j in major_diagonals, i + j in minor_diagonals]) | |
def add_candidate(i, j): | |
columns.append(j) | |
major_diagonals.add(i - j) | |
minor_diagonals.add(i + j) | |
def remove_candidate(i, j): | |
columns.pop() | |
major_diagonals.remove(i - j) | |
minor_diagonals.remove(i + j) | |
columns, major_diagonals, minor_diagonals = [], set(), set() | |
solutions = [] | |
solve() | |
return solutions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment