标签:note time may hat lower must queue sam find
问题描述:
Given two words (beginWord and endWord), and a dictionary‘s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Note:
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.
Example 2:
Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
解题思路:
这道题用BFS来解会更快找到答案,因为我们要找的是最短的变化。
我们可以对当前单词的每一个字母进行替换并且去判断新产生的单词是否在wordList里,为了能够快速判断是否在wordList里,我们用一个set来存储wordList里的单词。
用map来存储从beginWord到该word的步数。
用queue来辅助我们进行bfs,提出队首位置的单词,对单词每一个字母进行变换尝试,在变化中记得要检查以下内容:
1.是否是endWord
2.是否是wordList里的单词:
a.若不是,则可以进行下一个尝试
b.若是,则检查是否在map里出现过,若出现过,则表明我们已经访问过该单词,再次访问会出现环;若没有出现过,则表明这是一个可能的单词,将其压入队中。
在bfs的时候我们要检查是否是endWord,如果是的话就返回map[word]+1。
代码:
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> dict(wordList.begin(), wordList.end()); unordered_map<string, int> m; queue<string> q; m[beginWord] = 1; q.push(beginWord); while(!q.empty()){ string word = q.front(); q.pop(); for(int i = 0; i < word.size(); ++i){ string newWord = word; for(char c = ‘a‘; c <= ‘z‘; c++){ newWord[i] = c; if(dict.count(newWord) && newWord == endWord){ return m[word]+1; } if(dict.count(newWord) && !m.count(newWord)){ q.push(newWord); m[newWord] = m[word]+1; } } } } return 0; } };
标签:note time may hat lower must queue sam find
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9189885.html