[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学习打卡-Day23】从重复到重用:用Pipeline和ColumnTransformer重构你的机器学习工作流
python·学习·重构
Swift社区5 小时前
LeetCode 451 - 根据字符出现频率排序
算法·leetcode·ssh
棒棒的皮皮5 小时前
【OpenCV】Python图像处理之平滑处理
图像处理·python·opencv·计算机视觉
Kurbaneli5 小时前
Python列表推导式保姆级教程
python
Hello eveybody5 小时前
用代码生成电影预告片
python
LYFlied5 小时前
【每日算法】LeetCode 22. 括号生成
数据结构·算法·leetcode·面试·职场和发展
2401_841495645 小时前
【自然语言处理】汉字表管理工具
人工智能·python·自然语言处理·初始化·数据关联·汉字表管理工具·批量操作到版本控制
BoBoZz195 小时前
Finance利用 高斯溅射和 等值面提取技术可视化金融数据
python·vtk·图形渲染·图形处理
小智RE0-走在路上5 小时前
Python学习笔记(5)--函数
笔记·python·学习
棒棒的皮皮5 小时前
【OpenCV】Python图像处理之重映射
图像处理·python·opencv·计算机视觉