Leetcode #212 Trie Tree + Backtracking

226 阅读1分钟

又要开始找实习了🤯 今天开始打卡🥳 DAY 1

题目

#212 Word Search II

思路

只用backtracking的话time limit应该会超,所以先把word lists变成trie tree,如何再整体backtrack

# Trie Node
class node(object):
    def __init__(self):
        self.val = "*"
        self.child = [None]*26
        self.isLeaf = False

# Trie Tree
class trie(object):
    def __init__(self):
        self.root = node()

    def insertRecur(self, tree, word):
        if (len(word) == 0):
            tree.isLeaf = True
        else:
            w = ord(word[0])-97
            if (not tree.child[w]):
                new = node()
                new.val = word[0]
                new.isLeaf = False
                tree.child[w] = new
            self.insertRecur(tree.child[w], word[1:])

    def insert(self, word):
        self.insertRecur(self.root, word)                

class Solution(object):
    def findWords(self, board, words):
        """
        :type board: List[List[str]]
        :type words: List[str]
        :rtype: List[str]
        """
        trieTree = trie()
        for word in words:
            trieTree.insert(word)

        # 邻居的四个方向
        dir = [(-1,0), (1,0), (0,-1),(0,1)]
        # 记录结果
        result = []        

        # 判断是不是board里面的valid index
        def isValidBoardIndex(i,j):
            return (i >= 0 and j >= 0 and i < len(board) and j < len(board[0]))

        # (i,j)代表board内的board[i][j]
        def backtracking(i, j, trieNode, word, visited):
            # 如果
            if (trieNode.val != board[i][j]):
                return None
            word += trieNode.val
            if (trieNode.isLeaf):
                if (word not in result):
                    result.append(word)
            for d in dir:
                tmpi = i+d[0]
                tmpj = j+d[1]
                # 判断现在是不是valid index, 且没有visit过
                if (isValidBoardIndex(tmpi, tmpj) and (tmpi, tmpj) not in visited):
                    visited.add((tmpi, tmpj))
                    for child in trieNode.child:
                        orginalVisited = visited.copy()
                        if (child):
                            tmp = backtracking(tmpi, tmpj, child, word, visited)
                        visited = orginalVisited
                    visited.remove((tmpi,tmpj))

        for i in range(len(board)):
            for j in range(len(board[0])):
                for child in trieTree.root.child:
                    if (child):
                        visit = set()
                        visit.add((i,j))
                        backtracking(i,j,child,"",visit)
        return result

还是挺慢 但是不想管了🥱