Skip to content

Instantly share code, notes, and snippets.

@cod3smith
Created June 4, 2023 19:18
Show Gist options
  • Save cod3smith/345d94effacfb67cf31f7c31640f556c to your computer and use it in GitHub Desktop.
Save cod3smith/345d94effacfb67cf31f7c31640f556c to your computer and use it in GitHub Desktop.
def solve_n_queens(n):
def is_safe(board, row, col):
# Check if a queen can be placed at the given position without conflicting
# with any other queens on the board
for i in range(row):
if board[i] == col or \
board[i] - i == col - row or \
board[i] + i == col + row:
return False
return True
def backtrack(board, row):
# Base case: all queens have been placed successfully
if row == n:
return 1
count = 0
for col in range(n):
if is_safe(board, row, col):
board[row] = col
count += backtrack(board, row + 1)
board[row] = -1
return count
# Initialize the board with empty cells
board = [-1] * n
return backtrack(board, 0)
n = 4
count = solve_n_queens(n)
print(f"Number of possible arrangements for {n}-queens: {count}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment