Skip to content

feat: Implement N-Queens problem solution using backtracking #196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions n_queens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
def is_safe(board, row, col, N):
# Check if there's a queen in the same column
for i in range(row):
if board[i][col] == 1:
return False

# Check upper-left diagonal
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check upper-right diagonal
for i, j in zip(range(row, -1, -1), range(col, N)):
if board[i][j] == 1:
return False

return True

def solve_n_queens(N):
board = [[0 for _ in range(N)] for _ in range(N)]
if solve_util(board, 0, N) is False:
print("No solution exists")
else:
print_solution(board)

def solve_util(board, row, N):
if row == N:
return True

for col in range(N):
if is_safe(board, row, col, N):
board[row][col] = 1

if solve_util(board, row + 1, N):
return True

board[row][col] = 0 # Backtrack

return False

def print_solution(board):
for row in board:
print(" ".join(["Q" if cell == 1 else "." for cell in row]))

N = 8 # Change N to solve for different board sizes
solve_n_queens(N)