leetcode127 - Word Ladder - medium
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:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
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分层。
循环很多:
while循环每一层(当前queue size,也就是都是上一层push进来的,切记size提前get出来):
第一个for循环层内每个单词:
第二个for循环当前单词内每个pos:
第三个for循环试图替换当前pos为26个字母中个任一:
放进queue的条件是:修改了这个位置成这个字母后,得到一个在dict里的单词
(check if it's a neighbor: connected by one transformation(an edge))
track visited node可以先把所有dict词都参考进来,每次用到了的话把它从set里删掉,就同时保证了(在dict里)和(没用过)这两个条件
实现:~O(mn) m-longest word, n-numWords
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> dict(wordList.begin(), wordList.end()); queue<string> q; q.push(beginWord); int ladder = 1; while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { string cur = q.front(); q.pop(); if (cur == endWord) return ladder; dict.erase(cur); for (int j = 0; j < cur.size(); j++) { char copy = cur[j]; for (int k = 0; k < 26; k++) { cur[j] = 'a' + k; if (dict.find(cur) != dict.end()) { q.push(cur); dict.erase(cur); } } cur[j] = copy; } } ladder++; } return 0; } };