1
그래서 n-queens 문제를 해결하고이 역 추적 솔루션을 작성했습니다.n-queens를 푸는 동안 이상한 일
print board,'before'
board[each_row][column] = 'Q'
print board,' after'
이 문장은 'Q'로 같은 열에서 모든 인덱스를 변경하는 대신 특정 행에 그것을 변화 :
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)
이상한 것은 내가 쓴 라인 34, 35, 36 및 열 인덱스. 출력에서
:
[[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
일 뭐죠? 아니면 그냥 취 했니?
아! 젠장! 그걸 몰랐어. 2 차원 배열을 만드는 것이 멋진 트릭이라고 생각했습니다. 정말 고마워요! 나는 이것에 너무 많은 시간을 보냈다 : \ – yask
그것은 나를 전에 물린 잡았다. :-) 가능한 수정을 위해 편집을 참조하십시오. – smarx
왜 그런가? (? – yask