<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p>

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

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/07/search1.jpg" style="width: 322px; height: 322px;" />
<pre>
<strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;]
<strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/07/search2.jpg" style="width: 162px; height: 162px;" />
<pre>
<strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;]
<strong>Output:</strong> []
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == board.length</code></li>
	<li><code>n == board[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 12</code></li>
	<li><code>board[i][j]</code> is a lowercase English letter.</li>
	<li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= words[i].length &lt;= 10</code></li>
	<li><code>words[i]</code> consists of lowercase English letters.</li>
	<li>All the strings of <code>words</code> are unique.</li>
</ul>

class TrieNode:

    def __init__(self):

        self.childs = {}
        self.end_word = False
        self.word = None # at end word node, also save the word

class Trie:

    def __init__(self):
        self.root = TrieNode()

    def add_word(self, word):

        node = self.root
        for char in word:
            if char not in node.childs:
                node.childs[char] = TrieNode()
            node = node.childs[char]
        # for last char in the word, change the flag and save the word info
        node.end_word = True
        node.word = word

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:

        def backtrack(row, col, parent_node):

            cur_char = board[row][col]
            cur_node = parent_node.childs[cur_char]

            # Check 1: return case
            if cur_node.end_word:
                self.res.add(cur_node.word)
                # Optimization 1: after we find a word, we can change the end_word flag, to avoid check it again
                cur_node.end_word = False
            
            # Check 2: possible trim down the exploring scope
            # if current node has no children, we should removed this node from Trie to avoid checking it again
            if not cur_node.childs:
                parent_node.childs.pop(cur_char)
                return

            # Check 3: before exploring neighbors, mark current cell as visited for following call stacks
            board[row][col] = '$'
            dirs = [(0, 1), (0, -1), (1, 0), (-1,0)]

            for dx, dy in dirs:
                new_row, new_col = row + dx, col + dy
                if 0 <= new_row < self.M and 0 <= new_col < self.N and board[new_row][new_col] in cur_node.childs:
                    # explore next char
                    backtrack(new_row, new_col, cur_node)

            # backtrack/restore the original value
            board[row][col] = cur_char

        # 1. Init
        self.M = len(board)
        self.N = len(board[0])
        self.res = set()

        # 2. Build Trie by adding words
        t = Trie()
        for word in words:
            t.add_word(word)
        
        # 3. Iterate each cell on the board, check if we can find a word using this cell as the first char of a word
        for i in range(self.M):
            for j in range(self.N):
                if board[i][j] in t.root.childs:
                    backtrack(i, j, t.root)

        # 4. Return, change the set back to list
        return list(self.res)

18300