码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Word Search II

时间:2020-02-03 09:45:19      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:str   leetcode   前缀树   oar   高级   find   add   pre   ack   

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

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

标签:str   leetcode   前缀树   oar   高级   find   add   pre   ack   

原文地址:https://www.cnblogs.com/lautsie/p/12254383.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!