Last active
September 28, 2021 05:38
-
-
Save zedchance/56f315dddcaed9e7b93a2b187c8e9024 to your computer and use it in GitHub Desktop.
Place n queens on a nxn chess board, where no queen can attack another
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
# Place n queens on a nxn chess board, where no queen can attack another | |
def make_board(n): | |
return [[0 for i in range(n)] for i in range(n)] | |
def print_board(board): | |
for row in board: | |
for col in row: | |
print(str(col) + " ", end="") | |
print() | |
def place_queens(board): | |
n = len(board) | |
cols = [i for i in range(n)] | |
def placeable(row, col): | |
# check row | |
for r in board[row]: | |
if r == 1: | |
return False | |
# check col | |
for c in board: | |
if c[col] == 1: | |
return False | |
# check diags | |
## up left | |
r, c = row - 1, col - 1 | |
while r > -1 and c > -1: | |
if board[r][c] == 1: | |
return False | |
else: | |
r -= 1 | |
c -= 1 | |
## up right | |
r, c = row - 1, col + 1 | |
while r > -1 and c < n: | |
if board[r][c] == 1: | |
return False | |
else: | |
r -= 1 | |
c += 1 | |
# valid | |
return True | |
def drop(l, item): | |
new = l.copy() | |
new.remove(item) | |
return new | |
def _place_queens(row, cols): | |
if len(cols) == 0: | |
print("SOLUTION:") | |
print_board(board) | |
exit(0) # remove to find ALL solutions | |
else: | |
for col in cols: | |
if placeable(row, col): | |
# choose | |
board[row][col] = 1 | |
# explore | |
_place_queens(row + 1, drop(cols, col)) | |
# unchoose | |
board[row][col] = 0 | |
_place_queens(0, cols) | |
if __name__ == '__main__': | |
board = make_board(8) | |
place_queens(board) | |
Author
zedchance
commented
Sep 15, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment