【发布时间】:2022-08-21 12:11:25
【问题描述】:
我想制作一个可以输入的程序:
- 棋盘尺寸(宽高)
- 骑士到达任意方格的最大移动次数
- 骑士的起始位置
我想要这种格式:
尺寸:10 移动:2 骑士:2,4
2. . 1 2 1 。 . 2.
. 2 1 2 。 2 1 2 。 .
2. 2. 0 . 2. 2.
. 2 1 2 。 2 1 2 。 .
2. . 1 2 1 。 . 2.
. 2. 2. 2. 2. .
. . 2. 2. 2. . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
上面的数字是进入该区域的移动次数。 我的问题是我不知道如何在棋盘上写下每个方格所走的相应数字,并且无法将其限制为特定值,这样程序甚至不会继续寻找方格达到规定限度后。
下面的代码现在使用 \'X\' 代替数字,并使用 \'.\' 代替骑士的位置。 0\'s 是 \'.\' 的占位符,用于指示空白点。
这是我的代码:
chess_board = []
size = 10
for i in range(size):
row = []
for j in range(size):
row.append(0)
chess_board.append(row)
def print_board():
for i in range(size):
for j in range(size):
print(chess_board[i][j], end=\" \")
print(\"\\n\")
def get_possibilities(x, y):
pos_x = (2, 1, 2, 1, -2, -1, -2, -1)
pos_y = (1, 2, -1, -2, 1, 2, -1, -2)
possibilities = []
for i in range(len(pos_x)):
if x+pos_x[i] >= 0 and x+pos_x[i] <= (size-1) and y+pos_y[i] >= 0 and y+pos_y[i] <= (size-1) and chess_board[x+pos_x[i]][y+pos_y[i]] == 0:
possibilities.append([x+pos_x[i], y+pos_y[i]])
return possibilities
def solve():
counter = 2
x = 2
y = 4
chess_board[x][y] = \'.\'
for i in range((size*2)-1):
pos = get_possibilities(x, y)
minimum = pos[0]
for p in pos:
if len(get_possibilities(p[0], p[1])) <= len(get_possibilities(minimum[0], minimum[1])):
minimum = p
x = minimum[0]
y = minimum[1]
chess_board[x][y] = \'x\'
counter += 1
solve()
print_board()
标签: python knights-tour