I am trying to solve the n-queens problem. I wrote a solution for the problem as follows:
def isSafe(board,row,col):
for i in range(row):
if board[i][col]==1:
return False
x,y = row,col
# print(x,y)
while x>=0 and y>=0:
if board[x][y]==1:
return False
x-=1
y-=1
x,y = row,col
# print(x,y)
while x>=0 and y<len(board):
if board[x][y]==1:
return False
x-=1
y+=1
return True
def solveNQueens(n):
ans = []
def placeQueens(board,row):
if row==len(board):
ans.append(board)
return
for i in range(len(board)):
if isSafe(board,row,i):
board[row][i]=1
# print(board)
placeQueens(board,row+1)
board[row][i]=0
return
board = [[0 for i in range(n)] for j in range(n)]
# print(board)
placeQueens(board,0)
print(ans)
solveNQueens(4)
The above code uses recursive backtracking to solve the n queens problem. The placeQueens function appends the board combination directly to ans list when all the queens are assigned a row but when I try to print ans, all the places are marked as zeroes.
e.g for n=4:
Expected ans = [[[0,1,0,0],[0,0,0,1],[1,0,0,0],[0,0,1,0]],[[0,0,1,0],[1,0,0,0],[0,0,0,1],[0,1,0,0]]]
Answer printed = [[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]]
Where am I going wrong??
I tried appending the board positions one by one to the ans list and the code works fine.
def isSafe(board,row,col):
for i in range(row):
if board[i][col]==1:
return False
x,y = row,col
# print(x,y)
while x>=0 and y>=0:
if board[x][y]==1:
return False
x-=1
y-=1
x,y = row,col
# print(x,y)
while x>=0 and y<len(board):
if board[x][y]==1:
return False
x-=1
y+=1
return True
def solveNQueens(n):
ans = []
def placeQueens(board,row):
if row==len(board):
ans.append([])
# print(board)
for i in range(len(board)):
ans[-1].append([])
for j in board[i]:
if j==0:
ans[-1][-1].append(0)
else:
ans[-1][-1].append(1)
return
for i in range(len(board)):
if isSafe(board,row,i):
board[row][i]=1
# print(board)
placeQueens(board,row+1)
board[row][i]=0
return
board = [[0 for i in range(n)] for j in range(n)]
# print(board)
placeQueens(board,0)
print(ans)
solveNQueens(4)
Why is the first code generating incorrect output, when both the codes are logically similar??