剣指オファー(12)------マトリックス内のパス

'' ' 
0:左
1:右
2:上
3:下
' '' 
パス= [] 
def path_in_matrix(matrix、s):
    row、col = len(matrix)、len(matrix [0])
    グローバルパスパス
    = [] 
    if len(s)== 0:
        trueを返す
    def go_next(matrix、i、j、s、src):
        if len(s)== 0:
            trueを返す
        i> =行またはj> = colまたはmatrix [i] [j]!= s [0]:
            false 

        path.append((i、j))
        if src!= 0 and go_next(matrix、i、j-1、s [1:]、1)を返す:
            Trueを返す

        !SRC = 1とgo_next場合(行列、I、J + 1 [1:]、S、0):
            trueを返します

        if src!= 2およびgo_next(matrix、i-1、j、s [1:]、3):
            trueを返す

        if src!= 3およびgo_next(matrix、i + 1、j、s [1:]、2 ):
            True 

        パスを返します。pop()
    は、範囲(行)のiに対して
        false 
返します範囲(列)の
        jに対して:
            マトリックス[i] [j] == s [0]:
                パス.append((i、j ))
                if go_next(matrix、i、j-1、s [1:]、1):#go from right 
                    return true 
                if go_next(matrix、i、j + 1、s [1:]、0):#go 
                go_next(matrix、i-1、j、s [1:]、3)の場合、左から
                    True 返します:#下から移動 
                    リターン真
                if go_next(matrix、i + 1、j、s [1:]、2):#go from up 
                    return true 
                paths.pop()
    return False 

if __name__ == " __main__ ":
    matrix = [['a'、 ' b '、' t '、' g ']、
              [' c '、' f '、' c '、' s ']、
              [' j '、' d '、' e '、' h ']、
             ] 
    印刷(path_in_matrix(matrix、 'bfce'))
    print(paths)
    print(path_in_matrix(matrix、 'abfb'))
    print(paths)
    print(path_in_matrix(matrix、 'tceh'))
    print(paths)
公開された230元の記事 ウォンの賞賛160 ビュー820 000 +

おすすめ

転載: blog.csdn.net/happyAnger6/article/details/104762523