Skip to content
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

Nqueens #3538

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Nqueens #3538

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
54 changes: 54 additions & 0 deletions Nqueens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
n=int(input('Enter number of queens:'))
def solveNQueens(n):
# Initialize the board as a 2D list of zeros
board = [[0 for _ in range(n)] for _ in range(n)]

def isSafe(row, col):
# Check if any queens already placed in the same row
for i in range(col):
if board[row][i] == 1:
return False

# Check if any queens already placed in the same upper diagonal
i, j = row, col
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1

# Check if any queens already placed in the same lower diagonal
i, j = row, col
while i < n and j >= 0:
if board[i][j] == 1:
return False
i += 1
j -= 1

# If no conflicts found, then the position is safe
return True

def solveHelper(col):
# Base case: If all queens are placed, return True
if col == n:
return True

# Recursive case: Try placing queen in each row of current column
for row in range(n):
if isSafe(row, col):
board[row][col] = 1
if solveHelper(col + 1):
return True
board[row][col] = 0

# If no safe position found, backtrack
return False

# Call the helper function to solve N-Queens problem
if solveHelper(0):
# Print the board
for row in board:
print(row)
else:
print("No solution exists for N =", n)
solveNQueens(n)