Python:Knight在0-63 Chessboard上的最短路径

时间:2016-12-04 04:10:50

标签: python arrays numpy shortest-path

问题:

给定输入(x,y),在编号为0-63的棋盘上找到骑士从x到y的最短路径(第1行:0-8,第2行:9-15等)。

我开始使用Numpy解决这个问题,但是1.事实证明我不允许使用Numpy,而且2.我的代码无论如何都变得太复杂了。必须有一种更简单的方法来解决这个问题。

这是我的(未完成的)代码,它解决了BFS搜索的前两个步骤:

import numpy as np

a = np.array([[0,1,2,3,4,5,6,7],
[8,9,10,11,12,13,14,15],
[16,17,18,19,20,21,22,23],
[24,25,26,27,28,29,30,31],
[32,33,34,35,36,37,38,39],
[40,41,42,43,44,45,46,47],
[48,49,50,51,52,53,54,55],
[56,57,58,59,60,61,62,63]])



def answer(src, dest):
''' Takes integer inputs, converts them to board coordinates '''
    x = np.argwhere(a==src)
    y = np.argwhere(a==dest)
    z = [tuple(l) for l in x]

''' Returns all possible moves from starting position, in coordinates '''
def knight_move(p):
    offset1 = np.array([[-2,-1],[-2,1],[2,-1],[2,1]])    
    idx = np.row_stack((offset1, offset1[:,::-1])) + p    
    return idx[~((idx < 0) | (idx > 7)).any(1)]

''' Checks smallest number of moves from start to end position '''
for i in z:
    mv1 = knight_move(i) #finds possible first moves
    b = a[mv1[:,0], mv1[:,1]] #converts from coordinates to integers
    if dest in b:
        return 1
    elif dest not in b:
        c = np.array(mv1).tolist() #converts mv1 to iterable list
        d = [tuple(e) for e in c] #converts list to tuples for knight_move
        blah = np.concatenate([knight_move(f) for f in d]).tolist() #returns coordinates of all possible second moves
        r = [tuple(m) for m in blah]
        h = np.asarray(r)
        w = a[h[:,0], h[:,1]]
        if dest in w:
            return 2

我知道我正以错误的方式攻击这个。我假设有一个相对简单的方法,我只是不知道。如何,只使用标准的python库(或根本不使用任何),我可以解决这个问题吗?

0 个答案:

没有答案