212. Word Search II

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

class TrieNode: 
    def __init__(self): 
        self.is_leaf = False 
        self.children = {} 
        self.word = None 

class TrieTree: 
    def __init__(self): 
        self.root = TrieNode() 
        self.word = False 
    def insert(self, s): 
        cur = self.root 
        for c in s: 
            if c not in cur.children: 
                cur.children[c] = TrieNode() 
            cur = cur.children[c] 
        cur.word = s 
        
class Solution: 
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: 
        tree = TrieTree() 
        for word in words: 
            tree.insert(word) 
        dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)] 
        m, n = len(board), len(board[0]) 
        ans = [] 
        def backtrack(i, j): 
            nonlocal root 
            letter = board[i][j] 
            if letter not in root.children: 
                return 
            oldroot = root 
            root = root.children[letter] 
            board[i][j] = '#' 
            if root.word: 
                ans.append(root.word) 
                root.word = None 
            for dx, dy in dirs: 
                if 0 <= i + dx < m and 0 <= j + dy < n and board[i + dx][j + dy] != '#': 
                    backtrack(i + dx, j + dy) 
            board[i][j] = letter 
            root = oldroot 
        for i in range(m): 
            for j in range(n): 
                root = tree.root 
                backtrack(i, j) 
        return ans