为什么我的代码不能用于N个皇后?

时间:2017-10-14 16:16:22

标签: python adjacency-matrix n-queens

我得到了这个代码,基本上如果我输入:0 1然后1将被分配到这个邻接矩阵的位置0 1我命名为chessboard.Problem用于大小为4x4的chesboard,如果我输入

1 0, 
3 1,
0 2,
2 3 

它应该输出

[[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]]

但是我收到错误'int'对象不支持此行中的项目分配:

chessboard[pos[0]][pos[1]] = 1

这是我的代码。

N = int ( input (" Enter N: ") ) # Makes an empty chessboard of size N by N
chessboard = N*[0]
for row in range (N) :
    chessboard[row]=N*[0]
    print(chessboard)
    # This while loop asks the user for input N times and checks that it ’s     validity and places the queens
    inputCount = 0
    while inputCount < N:
         pos = input (" Please input the Queen position ")
        pos = pos.split () # Cast the input as integers
        pos [0] = int (pos [0])
        pos [1] = int (pos [1])
# If the input is out of range , inform the user , decrement the counter set the input to 0 1
    if pos [0] < 0 or pos [0] >N-1 or pos [1] < 0 or pos [1] >N-1:
        print (" Invalid position ")
        pos [0] = pos [1] = 0
        inputCount=inputCount-1
    else :# Uses the input to place the queens
        chessboard[pos[0]][pos[1]] = 1
    inputCount += 1
print ( chessboard )

1 个答案:

答案 0 :(得分:2)

chessboard = N*[0]
for row in range (N) :
    chessboard[row]=N*[0]
    print(chessboard)

    # here you're still in the chessboard init loop

    inputCount = 0
    while inputCount < N:

您在初始化chessboard 时开始处理,而在开始后

由于chessboard首先是一个整数列表(为什么?),由循环中的整数列表替换,而你的循环只执行第一次迭代,你得到这个错误。

你需要从print(chessboard)

取消所有内容

但是如果没有像这样的循环初始化chessboard会更好(在外循环中使用列表推导而不是乘法,以生成每行的单独引用):

chessboard = [[0]*N for _ in range(N)]