蟒蛇骑士之旅特别节目



我想制作一个可以输入a:的程序

  • 棋盘大小(w和h(
  • 骑士到达任意方格的最大移动次数
  • 骑士的首发位置

我想要这种格式:

尺寸: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是"的占位符用来表示一个空位。

这是我的代码:

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

好吧,伙计们,因为没有人愿意帮忙,我设法为那些想要答案的人找到了答案。

possible_x = [1, 1, -1, -1, 2, 2, -2, -2]
possible_y = [2, -2, 2, -2, 1, -1, 1, -1]
board = []
def makeBoard(size, board):
for row in range(size):
row_list = []
for column in range(size):
row_list.append(". ")
board.append(row_list)
return board
def limit(size, x, y):
if(x >= 0 and x < size and y >= 0 and y < size):
return True
else:
return False

board = []
def moveKnight(size, x, y, check, limit_max, start_x, start_y):
for index in range(len(possible_x)):
if check >= limit_max:
break
nextX = possible_x[index] + x
nextY = possible_y[index] + y
if limit(size, nextX, nextY):
if '.' in board[nextX][nextY] or int(board[nextX][nextY].rstrip()) > check+1:
board[nextX][nextY] = str(check+1)+' '
moveKnight(size, nextX, nextY, check+1, limit_max, start_x, start_y)

board[start_x][start_y] = '0 '
size = int(input("Size: "))
moves = int(input("Moves: "))
knight_posX, knight_posY = input("Knight: ").split(",") 
board = makeBoard(size, board)
moveKnight(size, int(knight_posX), int(knight_posY), 0, moves, int(knight_posX), int(knight_posY))
print('n'.join([''.join(row).rstrip() for row in board]))

最新更新