剑指offer(12)------矩阵中的路径

'''
0:left
1:right
2:up
3:down
'''
paths = []
def path_in_matrix(matrix, s):
    row, col = len(matrix), len(matrix[0])
    global paths
    paths = []
    if len(s) == 0:
        return True
    def go_next(matrix, i, j, s, src):
        if len(s) == 0:
            return True
        if i >= row or j >= col or matrix[i][j] != s[0]:
            return False

        paths.append((i,j))
        if src != 0 and go_next(matrix, i, j-1, s[1:], 1):
            return True

        if src != 1 and go_next(matrix, i, j+1, s[1:], 0):
            return True

        if src != 2 and go_next(matrix, i-1, j, s[1:], 3):
            return True

        if src != 3 and go_next(matrix, i+1, j, s[1:], 2):
            return True

        paths.pop()
        return False

    for i in range(row):
        for j in range(col):
            if matrix[i][j] == s[0]:
                paths.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 from left
                    return True
                if go_next(matrix, i-1, j, s[1:], 3): #go from down
                    return 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'],
             ]
    print(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 · 访问量 82万+

猜你喜欢

转载自blog.csdn.net/happyAnger6/article/details/104762523