<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p>

<ul>
	<li>Every adjacent pair of words differs by a single letter.</li>
	<li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>
	<li><code>s<sub>k</sub> == endWord</code></li>
</ul>

<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>all the <strong>shortest transformation sequences</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]
<strong>Output:</strong> [[&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;],[&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]]
<strong>Explanation:</strong>&nbsp;There are 2 shortest transformation sequences:
&quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;
&quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;lot&quot; -&gt; &quot;log&quot; -&gt; &quot;cog&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;]
<strong>Output:</strong> []
<strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence.
</pre>

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

<ul>
	<li><code>1 &lt;= beginWord.length &lt;= 5</code></li>
	<li><code>endWord.length == beginWord.length</code></li>
	<li><code>1 &lt;= wordList.length &lt;= 500</code></li>
	<li><code>wordList[i].length == beginWord.length</code></li>
	<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>
	<li><code>beginWord != endWord</code></li>
	<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>
	<li>The <strong>sum</strong> of all shortest transformation sequences does not exceed <code>10<sup>5</sup></code>.</li>
</ul>

import queue


class QueuedWord(NamedTuple):
    """Word in processing queue"""

    word: str
    "Processed word"

    forward: bool
    "Search direction: forward/backward"

    level: int = 1
    "Level in path relative to beginning/end"


class WordHierarchyNode(NamedTuple):
    """Word in hierarchy tree"""

    children: Set = set()
    "Child words in hierarchy tree"

    level: int = 1
    "Level in hierarchy tree"

class Solution:
    def __init__(self):
        self.positionLetters = []
        self.wordNeighborsCache = {}
        self.wordSet = set()

        self.wordQueue = queue.Queue()
        self.forwardWordHierarchy: Dict[str, WordHierarchyNode] = {}
        self.backwardWordHierarchy: Dict[str, WordHierarchyNode] = {}

        self.forwardVisited = {}
        self.backwardVisited = {}

    def prepareData(self, beginWord: str, endWord: str, wordList: List[str]):
        self.positionLetters = []
        self.wordNeighborsCache = {}
        self.wordSet = set(wordList)

        for word in wordList:
            for i, c in enumerate(word):
                if i >= len(self.positionLetters):
                    self.positionLetters.append({c})
                elif c not in self.positionLetters[i]:
                    self.positionLetters[i].add(c)

        self.forwardWordHierarchy = {}
        self.backwardWordHierarchy = {}

        self.forwardVisited = {}
        self.backwardVisited = {}

        if not self.wordQueue.empty():
            self.wordQueue = queue.Queue()

        for w in self.findWordNeighbors(beginWord):
            self.forwardWordHierarchy[w] = WordHierarchyNode({beginWord})
            self.wordQueue.put(QueuedWord(w, True))

        for w in self.findWordNeighbors(endWord):
            self.backwardWordHierarchy[w] = WordHierarchyNode({endWord})
            self.wordQueue.put(QueuedWord(w, False))

    def findWordNeighbors(self, word: str) -> Set[str]:
        if word in self.wordNeighborsCache:
            return self.wordNeighborsCache[word]

        neighbors = set()
        for i, c in enumerate(word):
            for opt in self.positionLetters[i]:
                if c == opt:
                    continue
                w = word[:i] + opt + word[i + 1:]
                if w in self.wordSet:
                    neighbors.add(w)

        self.wordNeighborsCache[word] = neighbors
        return neighbors

    def visitNeighbor(self, qWord: QueuedWord, neighbor: str) -> bool:
        """Checking that this neighbor has not been visited before in this path"""
        visited = self.forwardVisited if qWord.forward else self.backwardVisited
        word = qWord.word
        if word in visited:
            if neighbor in visited[word]:
                return True
            else:
                visited[word].add(neighbor)
        else:
            visited[word] = {neighbor}
        return False

    def wordFound(self, qWord: QueuedWord) -> bool:
        if qWord.forward:
            return qWord.word in self.backwardWordHierarchy
        else:
            return qWord.word in self.forwardWordHierarchy

    def buildCrossPaths(self, point: str) -> List[List[str]]:
        forwardPaths = self.buildWordPaths(point, True)
        backwardPaths = self.buildWordPaths(point, False)
        return [forwardPath + backwardPath[1:] for forwardPath in forwardPaths for backwardPath in backwardPaths]

    def buildWordPaths(self, word: str, forward: bool) -> List[List[str]]:
        wordHierarchy = self.forwardWordHierarchy if forward else self.backwardWordHierarchy
        if word not in wordHierarchy:
            return [[word]]

        result = []
        node = wordHierarchy[word]

        for child in node.children:
            childPaths = self.buildWordPaths(child, forward)
            if forward:
                result += [childPath + [word] for childPath in childPaths]
            else:
                result += [[word] + childPath for childPath in childPaths]

        return result

    def wordProcessing(self, qWord: QueuedWord):
        word = qWord.word
        forward = qWord.forward
        level = qWord.level

        for neighbor in self.findWordNeighbors(word):
            if self.visitNeighbor(qWord, neighbor):
                continue

            neighborLevel = level + 1
            wordHierarchy = self.forwardWordHierarchy if forward else self.backwardWordHierarchy

            if word in wordHierarchy:
                if neighbor in wordHierarchy[word].children:
                    continue

            if neighbor in wordHierarchy:
                node = wordHierarchy[neighbor]
                if word in node.children:
                    continue
                if node.level == neighborLevel:
                    node.children.add(word)
            else:
                wordHierarchy[neighbor] = WordHierarchyNode({word}, neighborLevel)

            self.wordQueue.put(QueuedWord(neighbor, forward, neighborLevel))

    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
        if endWord not in wordList:
            return []

        # beginWord and endWord are adjacent
        if sum(b != e for b, e in zip(beginWord, endWord)) == 1:
            return [[beginWord, endWord]]

        self.prepareData(beginWord, endWord, wordList)

        result = []
        foundWords = set()
        foundLevel = 0
        foundForward = False

        # word queue processing
        while not self.wordQueue.empty():
            qWord = self.wordQueue.get()
            if foundLevel > 0:
                if qWord in foundWords or qWord.forward != foundForward or qWord.level > foundLevel:
                    continue
            if self.wordFound(qWord):
                foundWords.add(qWord)
                foundLevel, foundForward = qWord.level, qWord.forward
                result += self.buildCrossPaths(qWord.word)
            else:
                self.wordProcessing(qWord)

        return result

18500