[英]Weird thing while solving n-queens
So, I was solving n-queens problem and wrote this backtracking solution. 因此,我正在解决n皇后问题,并编写了此回溯解决方案。
def isSafe(row, col, board):
print board
for i in range(col):
if board[row][i] == 'Q':
print 'faled here'
return False
r_row = row-1
c_col = col-1
while r_row >= 0 and c_col >=0:
if board[c_row][c_col] == 'Q':
return False
c_row -=1
c_col -=1
row = row-1
col = col-1
while row < len(board) and col >=0:
if board[row][col] == 'Q':
return False
row+=1
col-=1
return True
def solveNQueen(column, board):
if column == len(board[0]):
print board
return True
for each_row in range(len(board)):
print each_row,column
if isSafe(each_row,column,board):
print board,'before'
board[each_row][column] = 'Q'
print board,' after'
if solveNQueen(column+1,board):
return True
else:
board[each_row][column] = 0
print 'failed'
return False
board = [[0]*5]*5
print solveNQueen(0,board)
The weird thing is line 34, 35 and 36 where I wrote: 奇怪的是我在第34、35和36行中写道:
print board,'before'
board[each_row][column] = 'Q'
print board,' after'
This statement is changing all indexes in the same column to 'Q' instead of changing it at a particular row and column index. 该语句将同一列中的所有索引更改为“ Q”,而不是在特定的行和列索引处将其更改。
From the output: 从输出:
[[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]] before
[['Q', 0, 0, 0, 0], ['Q', 0, 0, 0, 0], ['Q', 0, 0, 0, 0], ['Q', 0, 0, 0, 0], ['Q', 0, 0, 0, 0]] after
Whats going on? 这是怎么回事? Or am I just drunk?
还是我只是喝醉了?
The issue is board = [[0]*5]*5
. 问题是
board = [[0]*5]*5
。 This gives you five copies of the same list of five zeros. 这将为您提供五个零的相同列表的五个副本。
One possible fix: 一种可能的解决方法:
board = [x[:] for x in [[0] * 5] * 5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.