[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
        
相关推荐
羊小猪~~30 分钟前
深度学习基础--CNN经典网络之InceptionV3详解与复现(pytorch)
网络·人工智能·pytorch·python·深度学习·机器学习·cnn
深度学习lover43 分钟前
<项目代码>YOLO小船识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·小船识别
愚公搬代码2 小时前
【愚公系列】《Python网络爬虫从入门到精通》055-Scrapy_Redis分布式爬虫(安装Redis数据库)
数据库·爬虫·python
浅浅2802 小时前
numpy、pandas内存优化操作整理
数据结构·经验分享·python·学习·性能优化·numpy·pandas
拓端研究室TRL2 小时前
Python+AI提示词比特币数据预测:Logistic逻辑回归、SVC及XGB特征工程优化实践
开发语言·人工智能·python·算法·逻辑回归
就叫飞六吧2 小时前
Python自动化selenium-一直卡着不打开浏览器怎么办?
python·selenium·自动化
亚林瓜子2 小时前
AWS Elastic Beanstalk的部署Python Flask后端服务(Hello,World)
python·flask·aws·eb
weixin_307779132 小时前
实现AWS Step Function安全地请求企业内部API返回数据
开发语言·python·云计算·aws
zhangjipinggom3 小时前
怎么安装python3.5-以及怎么在这个环境下安装包
开发语言·python
格子先生Lab3 小时前
Java反射机制深度解析与应用案例
java·开发语言·python·反射