Skip to content

Instantly share code, notes, and snippets.

@ibeauregard
Last active May 6, 2022 14:42
Show Gist options
  • Save ibeauregard/51ea083331b75af4cadc5f20d3f66dd6 to your computer and use it in GitHub Desktop.
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.
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