簡體   English   中英

解決n皇后時的怪事

[英]Weird thing while solving n-queens

因此,我正在解決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)

奇怪的是我在第34、35和36行中寫道:

    print board,'before'
    board[each_row][column] = 'Q'
    print board,' after'

該語句將同一列中的所有索引更改為“ Q”,而不是在特定的行和列索引處將其更改。

從輸出:

[[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

這是怎么回事? 還是我只是喝醉了?

問題是board = [[0]*5]*5 這將為您提供五個零的相同列表的五個副本。

一種可能的解決方法:

board = [x[:] for x in [[0] * 5] * 5]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM