Created
June 4, 2023 19:18
-
-
Save cod3smith/345d94effacfb67cf31f7c31640f556c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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