<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 Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not words: return []
        m, n = len(board), len(board[0])
        size = len(words)
        trie = {}
        marker = "$"
        for word in words:
            if not word: continue
            node = trie
            for ch in word:
                node = node.setdefault(ch, {})
            node[marker] = word
        print(trie)
        DR = {(-1, 0), (0, -1), (1, 0), (0, 1)}

        def backtrack(r: int, c: int, node: dict) -> None:
            ch = board[r][c]
            curr = node[ch]
            word_match = curr.pop(marker, False)
            if word_match:
                ans.append(word_match)

            board[r][c] = '$'
            for dr, dc in DR:
                r1 = r + dr
                c1 = c + dc
                if r1 < 0 or r1 >= m or c1 < 0 or c1 >= n or board[r1][c1] not in curr:
                    continue
                # visited.add((r1, c1))
                backtrack(r1, c1, curr)
                # visited.remove((r1, c1))
            board[r][c] = ch
            if not curr:
                node.pop(ch)

        ans = []
        visited = set()
        for r in range(m):
            for c in range(n):
                if board[r][c] not in trie: continue                
                backtrack(r, c, trie)
        return ans

    def findWords5(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not board[0] or not words: return
        trie = {}
        marker = '$'
        directions = {(-1, 0), (0, -1), (1, 0), (0, 1)}        
        # build trie
        for word in words:
            node = trie
            for ch in word:
                node = node.setdefault(ch, {})
            node[marker] = word
        
        def dfs(r: int, c: int, node: dict) -> None:
            ch = board[r][c]
            curr = node.get(ch)
            if not curr: return
            wd = curr.pop(marker, False)
            if wd:
                res.append(wd)
            board[r][c] = '#'
            for dr, dc in directions:
                r1 = r + dr
                c1 = c + dc
                if r1 < 0 or r1 >= m or c1 < 0 or c1 >= n: continue
                if board[r1][c1] not in curr: continue
                dfs(r1, c1, curr)
            board[r][c] = ch
            if not curr:
                del node[ch]

        m, n = len(board), len(board[0])
        res = []
        for r in range(m):
            for c in range(n):
                if board[r][c] not in trie: continue
                dfs(r, c, trie)
        return res


    def findWords4(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not board[0]: return []
        # m, n = len(board), len(board[0])
        directions = {(-1, 0), (0, -1), (1, 0), (0, 1)}
        # build trie
        trie = {}
        wd_marker = "#"
        for word in words:
            node = trie
            for ch in word:
                node = node.setdefault(ch, {})
            node[wd_marker] = word
        
        # traverse
        def traverse(r: int, c: int, node: dict) -> None:
            # nonlocal m, n, wd_marker
            ch = board[r][c]
            if ch not in node: return
            curr = node[ch]
            word_matched = curr.pop(wd_marker, False)
            if word_matched:
                res.append(word_matched)
            board[r][c] = '$'
            for dr, dc in directions:
                r1 = r + dr
                c1 = c + dc
                if r1 < 0 or r1 >= m or c1 < 0 or c1 >= n: continue
                if board[r1][c1] not in curr: continue
                traverse(r1, c1, curr)
            board[r][c] = ch
            if not curr:
                node.pop(ch)

        m, n = len(board), len(board[0])
        res = []
        for r in range(m):
            for c in range(n):
                if board[r][c] not in trie: continue
                traverse(r, c, trie)
        return res

    def findWords3(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not board[0] or not words: return []
        m, n = len(board), len(board[0])
        directions = {(-1, 0), (0, -1), (1, 0), (0, 1)}
        # build tries
        tries = {}
        WORD_KEY = "$"
        for word in words:
            node = tries
            for ch in word:
                node = node.setdefault(ch, {})
            node[WORD_KEY] = word

        print(tries)
        
        def traverse(r: int, c: int, parent: dict) -> None:
            # nonlocal m, n, WORD_KEY
            ch = board[r][c]
            curr = parent[ch]
            word_match = curr.pop(WORD_KEY, False)
            # print(word_match)
            if word_match:
                res.append(word_match)
                # return
            board[r][c] = '#'
            for dr, dc in directions:
                r1 = r + dr
                c1 = c + dc
                if r1 < 0 or r1 >= m or c1 < 0 or c1 >= n: continue
                if board[r1][c1] not in curr: continue
                traverse(r1, c1, curr) 
            board[r][c] = ch

            if not curr:
                parent.pop(ch)

        res = []
        for r in range(m):
            for c in range(n):
                if board[r][c] not in tries: continue
                traverse(r, c, tries)
        return res

    def findWords2(self, board: List[List[str]], words: List[str]) -> List[str]:
        WORD_KEY = "$"

        trie = {}
        for word in words:
            node = trie
            for letter in word:
                # retrieve the next node; If not found, create a empty node.
                node = node.setdefault(letter, {})
            # mark the existence of a word in trie node
            node[WORD_KEY] = word
        print(trie)
        rowNum = len(board)
        colNum = len(board[0])

        matchedWords = []

        def backtracking(row, col, parent):

            letter = board[row][col]
            currNode = parent[letter]

            # check if we find a match of word
            word_match = currNode.pop(WORD_KEY, False)
            if word_match:
                # also we removed the matched word to avoid duplicates,
                #   as well as avoiding using set() for results.
                matchedWords.append(word_match)

            # Before the EXPLORATION, mark the cell as visited
            board[row][col] = "#"

            # Explore the neighbors in 4 directions, i.e. up, right, down, left
            for rowOffset, colOffset in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
                newRow, newCol = row + rowOffset, col + colOffset
                if (
                    newRow < 0
                    or newRow >= rowNum
                    or newCol < 0
                    or newCol >= colNum
                ):
                    continue
                if not board[newRow][newCol] in currNode:
                    continue
                backtracking(newRow, newCol, currNode)

            # End of EXPLORATION, we restore the cell
            board[row][col] = letter

            # Optimization: incrementally remove the matched leaf node in Trie.
            if not currNode:
                parent.pop(letter)

        for row in range(rowNum):
            for col in range(colNum):
                # starting from each of the cells
                if board[row][col] in trie:
                    backtracking(row, col, trie)

        return matchedWords

    def findWords1(self, board: List[List[str]], words: List[str]) -> List[str]:
        if not board or not board[0] or not words: return []
        m, n = len(board), len(board[0])
        directions = {(-1, 0), (0, -1), (1, 0), (0, 1)}

        def traverse(r: int, c: int, index: int, word: str) -> None:
            nonlocal m, n
            if index == len(word):
                res.append(word)
                return
            if index > len(word): return
            if r < 0 or r >= m or c < 0 or c >= n or (r, c) in visited or board[r][c] != word[index]: return
            visited.add((r, c))
            for dr, dc in directions:
                r1 = r + dr
                c1 = c + dc
                traverse(r1, c1, index + 1, word)
            visited.remove((r, c))
        
        res = []
        visited = set()
        for word in set(words):
            for i in range(m):
                for j in range(n):
                    if board[i][j] != word[0]: continue
                    traverse(i, j, 0, word)
        return list(set(res))
        
18500