剑指offer第12题:矩阵中的路径(难)

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

# -*- coding:utf-8 -*-
class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        for i, s in enumerate(matrix):
            if s == path[0] and self.visit([(i // cols, i % cols)], matrix, rows, cols, path):
                return True
        return False

    def visit(self, ans, matrix, rows, cols, path):
        if len(ans) == len(path):
            return True
        i, j = ans[-1]
        nex = [(ii, jj) for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
                if 0 <= ii < rows and 0 <= jj < cols and (ii, jj) not in ans and matrix[ii * cols + jj] == path[len(ans)]]

        return sum([self.visit(ans + [x], matrix, rows, cols, path) for x in nex])
 
 

使用回溯法或递归方法。

代码抄的,勉强看懂,把疑问标黄记录下来。

另,enumerate()函数。

猜你喜欢

转载自blog.csdn.net/zhangjiaxuu/article/details/80830109