[NeetCode 150] Word Ladder

Word Ladder

You are given two words, beginWord and endWord, and also a list of words wordList. All of the given words are of the same length, consisting of lowercase English letters, and are all distinct.

Your goal is to transform beginWord into endWord by following the rules:

You may transform beginWord to any word within wordList, provided that at exactly one position the words have a different character, and the rest of the positions have the same characters.
You may repeat the previous step with the new word that you obtain, and you may do this as many times as needed.
Return the minimum number of words within the transformation sequence needed to obtain the endWord, or 0 if no such sequence exists.

Example 1:

Input: beginWord = "cat", endWord = "sag", wordList = ["bat","bag","sag","dag","dot"]

Output: 4

Explanation: The transformation sequence is “cat” -> “bat” -> “bag” -> “sag”.

Example 2:

Input: beginWord = "cat", endWord = "sag", wordList = ["bat","bag","sat","dag","dot"]

Output: 0

Explanation: There is no possible transformation sequence from “cat” to “sag” since the word “sag” is not in the wordList.

Constraints:

1 <= beginWord.length <= 10
1 <= wordList.length <= 100

Solution

The “distance” of every transformation is 1 so it is OK to apply BFS for searching the shortest path. Because it will take O ( wordList.length 2 × beginWord.length 2 ) O(\text{wordList.length}^2\times\text{beginWord.length}^2) O(wordList.length2×beginWord.length2) to build up the graph inevitably, more advanced shortest path algorithm is not necessary.

At first, we put begin word into BFS queue and set the initial distance of 1. Then we keep getting the top word from queue and check whether it can reach out other unvisited words. If so, we add these new words into queue and set their corresponding distance to current distance+1. When we reach the end word during this process, we can return early. If we cannot reach end word after the queue is empty, it means the end word is not reachable.

Code

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        if beginWord == endWord:
            return 1
        vis_flag = {word: False for word in wordList}
        # dis = {word: 10000000 for word in wordList}
        vis_flag[beginWord] = True
        vis_flag[endWord] = False
        from queue import Queue
        bfs_queue = Queue()
        bfs_queue.put((beginWord, 1))
        def check(a, b):
            if a == b:
                return False
            cnt = 0
            for i in range(len(a)):
                if a[i] != b[i]:
                    cnt += 1
            return cnt == 1
        while not bfs_queue.empty():
            cur = bfs_queue.get()
            for word in wordList:
                if not vis_flag[word] and check(cur[0], word):
                    if word == endWord:
                        return cur[1] + 1
                    vis_flag[word] = True
                    bfs_queue.put((word, cur[1]+1))
        return 0
        

相关推荐

  1. [NeetCode 150] Valid Sudoku

    2024-07-15 07:40:05       20 阅读
  2. [NeetCode 150] Word Ladder

    2024-07-15 07:40:05       23 阅读
  3. [NeetCode 150] Redundant Connection

    2024-07-15 07:40:05       25 阅读
  4. [NeetCode 150] Longest Consecutive Sequence

    2024-07-15 07:40:05       21 阅读
  5. [NeetCode 150] Products of Array Discluding Self

    2024-07-15 07:40:05       23 阅读
  6. [NeetCode 150] Merge K Sorted Linked Lists

    2024-07-15 07:40:05       26 阅读
  7. LeetCode 150, 112, 130

    2024-07-15 07:40:05       19 阅读
  8. DAY 10 | 1047, (20,150)

    2024-07-15 07:40:05       52 阅读
  9. 面试经典150题(96-100)

    2024-07-15 07:40:05       54 阅读
  10. 面试经典150题(108-110)

    2024-07-15 07:40:05       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 07:40:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 07:40:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 07:40:05       57 阅读
  4. Python语言-面向对象

    2024-07-15 07:40:05       68 阅读

热门阅读

  1. nginx+lua 实现URL重定向(根据传入的参数条件)

    2024-07-15 07:40:05       20 阅读
  2. Vue2-案例tab切换栏高亮

    2024-07-15 07:40:05       25 阅读
  3. 项目管理·沟通管理

    2024-07-15 07:40:05       26 阅读
  4. CentOS Stream 卸载 Podman 并安装 Docker 的方法

    2024-07-15 07:40:05       21 阅读
  5. 关于 LayoutInflater.inflate 的取值结论

    2024-07-15 07:40:05       21 阅读
  6. Zynq7000系列FPGA中的DMA控制器的编程限制

    2024-07-15 07:40:05       19 阅读