0% found this document useful (0 votes)
4 views2 pages

N 4 Nqueens Problem

The document contains a Python implementation of the N-Queens problem, specifically for N=4. It includes functions to check if a queen can be safely placed on the board, to solve the problem using backtracking, and to print the solution. The output shows one of the possible arrangements of the queens on the board.

Uploaded by

cssanjaycs438
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

N 4 Nqueens Problem

The document contains a Python implementation of the N-Queens problem, specifically for N=4. It includes functions to check if a queen can be safely placed on the board, to solve the problem using backtracking, and to print the solution. The output shows one of the possible arrangements of the queens on the board.

Uploaded by

cssanjaycs438
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

N = 4

def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end=' ')
print()

def isSafe(board, row, col):


# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on left side


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

# Check lower diagonal on left side


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

return True

def solveNQUtil(board, col):


# Base case: If all queens are placed, then return true
if col >= N:
return True

for i in range(N):
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1

# Recur to place rest of the queens


if solveNQUtil(board, col + 1):
return True

# If placing queen in board[i][col] doesn't lead to a solution,


# then remove the queen (backtrack)
board[i][col] = 0

# If the queen cannot be placed in any row in this column, return false
return False

def solveNQ():
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

if not solveNQUtil(board, 0):


print("Solution does not exist")
return False

printSolution(board)
return True
# Driver program to test the above function
solveNQ()

output:

0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0

=== Code Execution Successful ===

You might also like