Leetcode 127. Word Solitaire 126. Word Solitaire II

Time:2021-8-13

127. Word Solitaire
126. Word Solitaire II

Preprocessing + breadth first traversal

This code does not time out, but it is very slow. The official explanation can use two-way search to improve the speed. I don’t write two-way code here

127 questions

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:

        if beginWord not in wordList:
            wordList.append(beginWord)
        if endWord not in wordList:
            return 0
        s = wordList.index(beginWord)
        e = wordList.index(endWord)
        f = [False] * len(wordList)
        import queue
        q = queue.Queue()
        f[s] = True
        q.put((s, 0, []))
        edges = {}
        for i, word in enumerate(wordList):
            w = list(word)
            for j in range(len(w)):
                t = w[j]
                w[j] = '*'
                ww = ''.join(w)
                if ww not in edges:
                    edges[ww] = []
                edges[ww].append(i)
                w[j] = t
        mins = -1
        # ans = []
        while not q.empty():
            cur, step, path = q.get()
            path.append(wordList[cur])
            f[cur] = True
            if cur == e:
                if mins == -1:
                    mins = step
                    return step+1
                # else:
                    # if mins < step:
                        # return ans
                # ans.append(path)
            w = list(wordList[cur])
            for j in range(len(w)):
                t = w[j]
                w[j] = '*'
                ww = ''.join(w)
                for x in edges[ww]:
                    if f[x] == False:
                        q.put((x, step+1, path[::]))
                w[j] = t
        return 0

126 questions

class Solution:
    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
        if beginWord not in wordList:
            wordList.append(beginWord)
        if endWord not in wordList:
            return []
        s = wordList.index(beginWord)
        e = wordList.index(endWord)
        f = [False] * len(wordList)
        import queue
        q = queue.Queue()
        f[s] = True
        q.put((s, 0, []))
        edges = {}
        for i, word in enumerate(wordList):
            w = list(word)
            for j in range(len(w)):
                t = w[j]
                w[j] = '*'
                ww = ''.join(w)
                if ww not in edges:
                    edges[ww] = []
                edges[ww].append(i)
                w[j] = t
        mins = -1
        ans = []
        while not q.empty():
            cur, step, path = q.get()
            path.append(wordList[cur])
            f[cur] = True
            if cur == e:
                if mins == -1:
                    mins = step
                else:
                    if mins < step:
                        return ans
                ans.append(path)
            w = list(wordList[cur])
            for j in range(len(w)):
                t = w[j]
                w[j] = '*'
                ww = ''.join(w)
                for x in edges[ww]:
                    if f[x] == False:
                        q.put((x, step+1, path[::]))
                w[j] = t
        return ans

Timeout code

127 questions

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        if beginWord not in wordList:
            wordList.append(beginWord)
        if endWord not in wordList:
            return 0
            # wordList.append(endWord)
        s = wordList.index(beginWord)
        e = wordList.index(endWord)
        f = [False] * len(wordList)
        import queue
        q = queue.Queue()
        f[s] = True
        q.put((s, 0, []))
        def can_go(w1, w2):
            c = 0
            assert len(w1) == len(w2)
            for i in range(len(w1)):
                if w1[i] != w2[i]:
                    c += 1
                    if c > 1:
                        return False
            return c == 1
        mins = -1
        while not q.empty():
            cur, step, path = q.get()
            path.append(wordList[cur])
            f[cur] = True
            if cur == e:
                if mins == -1:
                    mins = step
                    return step+1
            for i in range(len(wordList)):
                if i != cur and not f[i]:
                    if can_go(wordList[cur], wordList[i]):
                        q.put((i, step+1, path[::]))
        return 0

Welcome to my blog:   https://codeplot.top/
My blog topic classification: https://codeplot.top/categories/%E5%88%B7%E9%A2%98/