eye*_*eye 1 python matrix n-queens
在这里,我必须编写 N 皇后问题的代码,其中用户将输入棋盘的尺寸和皇后的位置。
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
Run Code Online (Sandbox Code Playgroud)
根据用户输入,我制作了候选解决方案(这是一个列表),其中候选解决方案的索引代表皇后的列,值代表皇后的行位置。
候选解如下:
[1, 3, 0, 2]
由此我制作了一个矩阵来表示皇后的位置:
0, 0, 1, 0
1, 0, 0, 0
0, 0, 0, 1
0, 1, 0, 0
Run Code Online (Sandbox Code Playgroud)
我的问题是我必须通过检查对角线来检查候选解决方案是否为真,并在解决方案为真时打印一条消息。
这是到目前为止我的代码,它将打印候选解决方案和显示皇后位置的矩阵:
#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)
Run Code Online (Sandbox Code Playgroud)
由于我是 Python 新手,非常感谢任何帮助。提前致谢。