[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

python 复制代码
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
        
相关推荐
西农小陈5 分钟前
python-译码(赛氪OJ)
开发语言·python·算法
编程阿布8 分钟前
python自动化脚本:让工作自动化起来
开发语言·python·数据分析·自动化
大棒槌~33 分钟前
python AES
python·aes加密解密
赴约星河36 分钟前
TensorBoard快速入门
pytorch·python
Keven__Java37 分钟前
Python-进阶-Excel基本操作
android·python·excel
blues_C38 分钟前
Python + Playwright(24):处理HTTPS错误
自动化测试·软件测试·python·测试工具·https·playwright
做程序员的第一天43 分钟前
RKNPU2从入门到实践 --- 【4】RKNN 模型构建【使用pycharm一步一步搭建RKNN模型】
linux·ide·人工智能·python·pycharm·rk3588·rknpu
shulu1 小时前
leetcode_002_两数相加解析
算法·leetcode·职场和发展
IT毕设梦工厂2 小时前
计算机毕业设计选题推荐-高校学术交流平台-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
zhangbin_2372 小时前
【Python机器学习】NLP词中的数学——词袋
开发语言·人工智能·python·机器学习·自然语言处理