[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
        
相关推荐
安特尼9 分钟前
招行数字金融挑战赛数据赛道赛题一
人工智能·python·机器学习·金融·数据分析
serve the people15 分钟前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
MarkHard1231 小时前
Leetcode (力扣)做题记录 hot100(34,215,912,121)
算法·leetcode·职场和发展
多多*1 小时前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
正在走向自律1 小时前
从0到1:Python机器学习实战全攻略(8/10)
开发语言·python·机器学习
西西弗Sisyphus2 小时前
Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
开发语言·python
Taichi呀2 小时前
PyCharm 快捷键指南
ide·python·pycharm
Kidddddult2 小时前
力扣刷题Day 46:搜索二维矩阵 II(240)
算法·leetcode·力扣
Stara05112 小时前
基于注意力机制与iRMB模块的YOLOv11改进模型—高效轻量目标检测新范式
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
Python猫3 小时前
付费专栏·Python潮流周刊电子书合集(epub、pdf、markdown)下载
python·计算机·pdf·电子书·资料