美文网首页
面试题12.矩阵中的路径_hn

面试题12.矩阵中的路径_hn

作者: 1只特立独行的猪 | 来源:发表于2020-03-21 15:13 被阅读0次

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的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

    解答方法

    方法一:dfs回溯法

    思路

    https://leetcode-cn.com/problems/word-search/solution/zai-er-wei-ping-mian-shang-shi-yong-hui-su-fa-pyth/

    代码

    class Solution:
        def exist(self, board: List[List[str]], word: str) -> bool:
            directs = [[-1,0],[1,0],[0,-1],[0,1]]
            m = len(board)
            if m == 0:
                return False
            n = len(board[0])
            mark = [[False for _ in range(n)] for _ in range(m)]
            def backtrack(x, y,index):
                if index == len(word) -1:
                    return board[x][y] == word[index]
                if board[x][y] == word[index]:
                    mark[x][y] = True
                    for direct in directs:
                        cur_x = x + direct[0]
                        cur_y = y + direct[1]
                        if cur_x >=0 and cur_x < m and cur_y >= 0 and cur_y < n and not mark[cur_x][cur_y] and backtrack( cur_x, cur_y,  index+1):
                            return True
                    mark[x][y] = False
                return False
    
            for i in range(m):
                for j in range(n):
                    if backtrack( i, j, 0):
                        return True
            return False
    

    时间复杂度

    O((m*n)^2)

    空间复杂度

    O(m*n)

    相关文章

      网友评论

          本文标题:面试题12.矩阵中的路径_hn

          本文链接:https://www.haomeiwen.com/subject/xwbyyhtx.html