解决n-queens

时间:2016-06-14 07:05:53

标签: python algorithm backtracking

所以,我正在解决n-queens问题并编写了这个回溯解决方案。

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&#39;而不是在特定的行和列索引处更改它。

从输出中:

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

怎么回事?或者我只是喝醉了?

1 个答案:

答案 0 :(得分:2)

问题是board = [[0]*5]*5。这为您提供了五个相同列表五个零的副本。

一种可能的解决办法:

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