Skip to content

Commit

Permalink
Merge pull request #2185 from sujurinki/master
Browse files Browse the repository at this point in the history
N QUEEN IN PYTHON
  • Loading branch information
fineanmol committed Oct 3, 2022
2 parents 8bddc27 + 8f0e538 commit f1d3e82
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions N QUEEN.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

global N
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):


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

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

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):

if col >= N:
return True

for i in range(N):

if isSafe(board, i, col):


board[i][col] = 1


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


board[i][col] = 0

return False



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

if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False

printSolution(board)
return True

solveNQ()


0 comments on commit f1d3e82

Please sign in to comment.