2015-12-17 28 views
0

我一直在研究骑士的巡回模拟,而且我一直对如何将Arnd Roth变更应用到我的python程序感到st st不安。这里的程序片段是计算的大部分内容,并通过董事会,前往最少可能的移动位置。我想改变的是,如果有多个位置的移动次数最少(即它们都有2次移动可能),我想通过测量它们的位置和中心之间的距离并选择一个离它最远。 我该怎么做呢?寻找距离棋盘中心最远的棋 - 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 

回答

2

nx*ny矩形板(从0开始的索引)的中心的位置(xy)的(Manhattan)距离是根本abs((nx-1)/2 - x) + abs((ny-1)/2 - y)

如果你想要​​距离,它会非常相似。