【发布时间】:2017-07-30 03:19:05
【问题描述】:
这里我要编写 N-Queens 问题,用户将输入棋盘的尺寸和皇后的位置。
Enter the dimension of the Chessboard: 4
Enter position of the Queen: 10
Enter position of the Queen: 31
Enter position of the Queen: 02
Enter position of the Queen: 23
并且根据用户输入,我制作了候选解决方案(这是一个列表),其中候选解决方案的索引代表皇后的列,值代表皇后的行位置。
候选解如下:
[1, 3, 0, 2]
据此,我制作了一个矩阵来表示皇后的位置:
0, 0, 1, 0
1, 0, 0, 0
0, 0, 0, 1
0, 1, 0, 0
我的问题是我必须检查候选解是否为真,通过检查对角线并在解为真时打印一条消息。
到目前为止,这是我的代码,它将打印候选解决方案和显示皇后位置的矩阵:
#Ask the user to input the dimension of the Chessboard(N)
N=int(input("Enter the dimension of the Chessboard: "))
#Creating a list of list with zeros in the dimension N*N
list_0=[0 for m in range(N)]
#Iterating for the length of N
for t in range(N):
#Creating a list for the input position values
position=[int(i) for i in input("Enter position of the Queen: ")]
x,y = position[0],position[1]
#The y position is the index of the list_0, where x is the value at the index position
list_0[y] = x
#Printing the list_0
print(list_0)
#Creating a list of list with zeros
list_matrix = [[0 for m in range(len(list_0))] for n in range(len(list_0))]
#Iterating through the list_0 to find the index and the value of the list_0
for element in range(len(list_0)):
x,y = element, list_0[element]
list_matrix[y][x] = 1
#Defining a list to print the candidate solution for N-Queen problen in matrix format
def printListInTableFormat(list_default):
#Looping through length of the list_default
for row in range(len(list_default)):
new_row=''.join(str(list_matrix[row]))
matrix=print(new_row.strip('[]'))
return matrix
#Printing the matrix
matrix = printListInTableFormat(list_matrix)
由于我是 Python 新手,非常感谢任何帮助。提前致谢。
【问题讨论】:
-
完成后,与此解决方案进行比较会很有趣:code.activestate.com/recipes/576647
-
嗯,这个问题和答案似乎在吸引反对票。 OP 付出了很大的努力,两个答案都将 OP 引向了正确的解决方案。不知道我看到了什么问题。
-
关于游戏的问题似乎会吸引某些方面的自动投反对票。