<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]:
        self.Troot = TNode(letter='root')
        self.board = board
        self.M, self.N = len(board), len(board[0])
        for w in words:
            self.addToRoot(w)
        
        res = []
        for m in range(self.M):
            for n in range(self.N):
                res += self.expand(m, n, curWord=board[m][n])
        return list(set(res))

    def expand(self, i, j, curWord, past_ij=None):
        res = []
        if past_ij is None:
            # base case first letter
            past_ij = set(((i, j), ))
            _, isWord = self.isPrefixAndWord(curWord)
            if isWord:
                res.append(curWord)
                self.deleteWord(curWord)

        for di, dj in ((0, 1), (0, -1), (1, 0), (-1, 0)):
            ni, nj = i+di, j+dj
            if ni < 0 or nj < 0 or ni >= self.M or nj >= self.N:
                continue
            elif (ni, nj) in past_ij:
                continue
            nword = curWord + self.board[ni][nj]
            isPrefix, isWord = self.isPrefixAndWord(nword)
            if not isPrefix:
                continue
            if isWord:
                res.append(nword)
                self.deleteWord(nword)
            res += self.expand(ni, nj, nword, past_ij | set(((ni, nj), )))
        return res

    def addToRoot(self, word):
        cur = self.Troot
        for l in word:
            cur = cur.addGetLetter(l)
        cur.isWord = True
    
    def isPrefixAndWord(self, word):
        cur = self.Troot
        for l in word:
            if l in cur.children:
                cur = cur.children[l]
            else:
                return False, False
        return True, cur.isWord
    
    def deleteWord(self, word):
        path = [self.Troot]
        cur = self.Troot
        for l in word:
            if l in cur.children:
                cur = cur.children[l]
                path.append(cur)
        cur.isWord = False
        for i in range(len(path)-1, 0, -1):
            if len(path[i].children) > 0 or path[i].isWord:
                break
            # no children
            del path[i-1].children[path[i].letter]



class TNode:
    def __init__(self, letter, parent=None):
        self.letter = letter
        self.parent = parent
        self.children = {}
        self.isWord = False
        self.toDelete = False
    
    def __repr__(self):
        r = self.letter
        ch = ['-' + repr(c) for c in self.children.values()]
        ch = '\n'.join(ch)
        ch = '\n'.join(['|' + line for line in ch.split('\n')])
        return r + '\n' + ch

    def addGetLetter(self, letter):
        if letter not in self.children:
            self.children[letter] = TNode(letter, parent=self)
        return self.children[letter]

19500