LeetcodeMedium-【面试题12. 矩阵中的路径】

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。

[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]

但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。

示例 1:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true


示例 2:

输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false


提示:

1 <= board.length <= 200
1 <= board[i].length <= 200
注意:本题与主站 79 题相同:https://leetcode-cn.com/problems/word-search/

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:深搜(dfs)

首先遍历数组,尝试每个点为起点,然后从起点的各个方向开始搜索,看能否找到一个路径。

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if board == [] or board == [[]]:
            return False 
        # 标记该点是否在本次路径中搜索过
        self.visit = [[0]*len(board[0]) for _ in range(len(board))]
        # 每个点的周边点,分别为x,y的变化值
        self.dx = [0, 0, 0, 1, -1]
        self.dy = [0, 1, -1, 0, 0]
        self.board = board
        self.word = word
        for i in range(len(board)):
            for j in range(len(board[0])):
                rt = self.dfs(i, j, 0)
                if rt == True:
                    return True
        return False
    def dfs(self, x, y, cnt):
        if cnt == len(self.word):
            return True
        for i in range(len(self.dx)):
            xx = x + self.dx[i]
            yy = y + self.dy[i]
            if xx >= 0 and xx < len(self.board) and yy >= 0 and yy < len(self.board[0]) and self.visit[xx][yy] == 0:
                if self.board[xx][yy] == self.word[cnt]:
                    self.visit[xx][yy] = 1
                    # print(xx, yy)
                    rt = self.dfs(xx, yy, cnt+1)
                    if rt == True:
                        return True
                    self.visit[xx][yy] = 0
        return False
发布了314 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39451578/article/details/105385140