Python算法之矩阵路径

Python算法之矩阵路径

问题:假设一个由字母构成的矩阵,我们需要知道在该矩阵中是否存在一条包含某些连续字符串的路径。路径可以从矩阵中的任意位置开始,如果存在,则返回True。否则,返回False。

例如:一个3X4的矩阵

Python算法之矩阵路径

现在有一个路径’wdg’,判断矩阵中是否包含该路径。

代码:

class MatrixPath():
    def printMatrix(self, matrix, rows, cols, direction):
        if direction:
            print('---' + direction)
        for i in range(rows):
            for j in range(cols):
                print(matrix[cols * i + j], end=' ')
            print()

    def hasPath(self, matrix, rows, cols, path):
        for i in range(rows):
            for j in range(cols):
                if matrix[i * cols + j] == path[0]:  # 找到起始点
                    if self.findPath(list(matrix), rows, cols, path[1:], i, j):
                        return True
        return False

    def findPath(self, matrix, rows, cols, path, x, y):
        if not path:
            return True
        # 将当前位置标记为已经走过
        matrix[x * cols + y] = '*'
        '''
            矩阵路径:东南西北四个方向
        '''
        # 向东走
        if y + 1 < cols and matrix[x * cols + y + 1] == path[0]:
            self.printMatrix(matrix, rows, cols, '向东走')
            return self.findPath(matrix, rows, cols, path[1:], x, y + 1)
        # 向西走
        elif y - 1 >= 0 and matrix[x * cols + y - 1] == path[0]:
            self.printMatrix(matrix, rows, cols, '向西走')
            return self.findPath(matrix, rows, cols, path[1:], x, y - 1)
        # 向南走
        elif x + 1 < rows and matrix[(x + 1) * cols + y] == path[0]:
            self.printMatrix(matrix, rows, cols, '向南走')
            return self.findPath(matrix, rows, cols, path[1:], x + 1, y)
        # 向北走
        elif x - 1 >= 0 and matrix[(x - 1) * cols + y] == path[0]:
            self.printMatrix(matrix, rows, cols, '向北走')
            return self.findPath(matrix, rows, cols, path[1:], x - 1, y)
        else:
            return False


if __name__ == '__main__':
    matrix = 'abcesfcswdgm'
    path = 'wdg'
    mp = MatrixPath()
    mp.printMatrix(matrix, 3, 4, None)
    print(mp.hasPath(list(matrix), 3, 4, path))

运行结果:

a b c e 
s f c s 
w d g m 
---向东走
a b c e 
s f c s 
* d g m 
---向东走
a b c e 
s f c s 
* * g m 
True


发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章