212. Word Search II - LeetCode Solution


BackTracking Trie

Python Code:

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        
       
        def inBounds(i, j):
            return 0 <= i < len(board) and 0 <= j < len(board[i])
        
        def dfs(i, j, trie, p):
            
            l = board[i][j]
            
            if l not in trie:
                return
            
            p.append(l)
            trie = trie[l]
            
            if "$" in trie:
                self.result.add("".join(p))
            
            for dx, dy in ((0, 1), (0, -1), (-1, 0), (1, 0)):
                di = i + dx
                dj = j + dy
                
                if inBounds(di, dj) and (di, dj) not in self.visited:
                    self.visited.add((di, dj))
                    dfs(di, dj, trie, p[:])
                    self.visited.remove((di, dj))
        
        self.visited = set()
        self.result = set()
        trie = self.buildTrie(words)
        for i in range(len(board)):
            for j in range(len(board[i])):
                self.visited.add((i, j))
                dfs(i, j, trie, [])
                self.visited.remove((i, j))

        return self.result
        
    def buildTrie(self, words):
        
        trie = {}
        head = trie
        
        for word in words:
            for letter in word:
                if letter not in trie:
                    trie[letter] = {}
                trie = trie[letter]
            trie['$'] = {}
            trie = head
        return trie
            
        


Comments

Submit
0 Comments
More Questions

1547C - Pair Programming
550A - Two Substrings
797B - Odd sum
1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition
1609C - Complex Market Analysis
1657E - Star MST
1143B - Nirvana
1285A - Mezo Playing Zoma
919B - Perfect Number
894A - QAQ
1551A - Polycarp and Coins
313A - Ilya and Bank Account
1469A - Regular Bracket Sequence
919C - Seat Arrangements
1634A - Reverse and Concatenate
1619C - Wrong Addition
1437A - Marketing Scheme
1473B - String LCM
1374A - Required Remainder
1265E - Beautiful Mirrors
1296A - Array with Odd Sum
1385A - Three Pairwise Maximums
911A - Nearest Minimums
102B - Sum of Digits
707A - Brain's Photos
1331B - Limericks
305B - Continued Fractions
1165B - Polycarp Training