0

我一直在研究骑士的巡回模拟,对于如何将 Arnd Roth 更改应用于我的 python 程序,我感到很困惑。这里的程序片段是计算的大部分,并通过棋盘,移动到可能移动次数最少的位置。我想改变的是,如果有多个位置的移动次数最少(即它们都有 2 个可能的移动),我想通过测量它们的位置和中心之间的距离并选择一个来打破它们之间的关系离它最远。我该怎么做呢?


    dx = [-2, -1, 1, 2, -2, -1, 1, 2]
dy = [1, 2, 2, 1, -1, -2, -2, -1]
# start the Knight from a random position
while tourTotal < tourMax:
    chessBoardX = chessX; chessBoardY = chessY # width and height of the chessboard
    chessBoard = [[0 for x in range(chessBoardX)] for y in range(chessBoardY)] # chessboard
# directions the Knight can move on the chessboard
    currentX = random.randint(0, chessBoardX - 1)
    currentY = random.randint(0, chessBoardY - 1)
    currentFailures = 0

    for k in range(chessBoardX * chessBoardY):
        chessBoard[currentY][currentX] = k + 1
        priorityQueue = [] # priority queue of available neighbors
        for i in range(8):
            newX = currentX + dx[i]; newY = currentY + dy[i]
            if newX >= 0 and newX < chessBoardX and newY >= 0 and newY < chessBoardY:
                if chessBoard[newY][newX] == 0:#if not visited
                    # count the available neighbors of the neighbor
                    counter = 0#counter is 0
                    for j in range(8):#max 8 moves
                        eX = newX + dx[j]; eY = newY + dy[j] #shows 1 move
                        if eX >= 0 and eX < chessBoardX and eY >= 0 and eY < chessBoardY:#if move is in parameters
                            if chessBoard[eY][eX] == 0: counter += 1 #if move is not visited, count is added
                    heappush(priorityQueue, (counter, i))#the amount of moves is pushed, along with the corresponding direction value
        # move to the neighbor that has min number of available neighbors
        if len(priorityQueue) > 0:
            (p, m) = heappop(priorityQueue)
            currentX += dx[m]; currentY += dy[m]
        else: break
4

1 回答 1

1

位置 ( , ) 到矩形板中心的( Manhattan ) 距离(从0 开始的索引)很简单。xynx*nyabs((nx-1)/2 - x) + abs((ny-1)/2 - y)

如果您想要欧几里得距离,它将非常相似。

于 2015-12-17T07:48:34.103 回答