leetcode-212-单词搜索②

题目描述:

leetcode-212-单词搜索②_第1张图片

 

 

 

 

第一次提交:(超出时间限制)

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        def dfs(word,i,j,visited):
            if len(word)==1 and word==board[i][j]:
                return True
            elif word[0]!=board[i][j]:return 
            else:
                list = [[i-1,j],[i+1,j],[i,j-1],[i,j+1]]
                for i,j in list:
                    if 0<=iand 0<=jand (i,j) not in visited:
                        if dfs(word[1:],i,j, visited|{(i, j)}):
                            return True
        res = []
        for word in words:
            for i in range(len(board)):
                for j in range(len(board[0])):
                    if dfs(word,i,j,{(i, j)}):
                        res.append(word)
        return list(set(res))
            
            

方法二:前缀树

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        trie = {}  # 构造字典树
        for word in words:
            node = trie
            for char in word:
                node = node.setdefault(char, {})
            node['#'] = True

        def search(i, j, node, pre, visited):  # (i,j)当前坐标,node当前trie树结点,pre前面的字符串,visited已访问坐标
            if '#' in node:  # 已有字典树结束
                res.add(pre)  # 添加答案
            for (di, dj) in ((-1, 0), (1, 0), (0, -1), (0, 1)):
                _i, _j = i+di, j+dj
                if -1 < _i < h and -1 < _j < w and board[_i][_j] in node and (_i, _j) not in visited:  # 可继续搜索
                    search(_i, _j, node[board[_i][_j]], pre+board[_i][_j], visited | {(_i, _j)})  # dfs搜索

        res, h, w = set(), len(board), len(board[0])
        for i in range(h):
            for j in range(w):
                if board[i][j] in trie:  # 可继续搜索
                    search(i, j, trie[board[i][j]], board[i][j], {(i, j)})  # dfs搜索
        return list(res)

 

你可能感兴趣的:(leetcode-212-单词搜索②)