繁体   English   中英

为什么我的代码对N个皇后不起作用?

[英]Why doesn't my code work for N queens?

我得到了这段代码,基本上如果我输入:0 1,那么将在这个称为棋盘的邻接矩阵上将0 1分配给位置0 1。问题是尺寸为4x4的棋盘,如果我输入

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 )
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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM