[leetcode]Word Search II

Posted 阿牧遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]Word Search II相关的知识,希望对你有一定的参考价值。

用了前缀集合,高级的可以用前缀树

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        if len(board) == 0 or len(board[0]) == 0:
            return []
        
        m = len(board)
        n = len(board[0])
        
        prefixSet = set()
        for word in words:
            for i in range(len(word)):
                prefixSet.add(word[ : i + 1])
                
        result = []
        
        for i in range(len(board)):
            for j in range(len(board[0])):
                visited = [[False] * n for k in range(m)]
                self.backtrace(board, visited, words, prefixSet, ‘‘, i, j, 0, result)
                
        result = sorted(result)
        return result
                
    def backtrace(self, board, visited, words, prefixSet, word, i, j, step, result):
        m = len(board)
        n = len(board[0])
        
        visited[i][j] = True
        word = word + board[i][j]
        
        if word in prefixSet:
            if word in words and word not in result:
                result.append(word)
            for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                if i + dx < 0 or i + dx >= m or j + dy < 0 or j + dy >= n:
                    continue
                if not visited[i + dx][j + dy]:
                    self.backtrace(board, visited, words, prefixSet, word, i + dx, j + dy, step + 1, result)
                    
        visited[i][j] = False

  

以上是关于[leetcode]Word Search II的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]Word Search II

leetcode 212. Word Search II Add to List 查找单词---------- java

算法:212. Word Search II单词搜索II

Word Search II

212. Word Search II

212. Word Search II