Skip to content

Instantly share code, notes, and snippets.

@zedchance
Last active September 28, 2021 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zedchance/56f315dddcaed9e7b93a2b187c8e9024 to your computer and use it in GitHub Desktop.
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
# 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)
@zedchance
Copy link
Author

SOLUTION:
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment