标签:from ems tran case path target class size max
Given two words (beginWord and endWord), and a dictionary‘s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Note:
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Example 2:
Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
Approach #1: DFS. [C++]
class Solution { public: vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> visited; unordered_set<string> wordList_(wordList.begin(), wordList.end()); vector<vector<string>> ans; queue<vector<string>> paths; paths.push({beginWord}); // record length of current shortest transformation sequence int level = 1; // record lenght of last conditional shortest transformation sequence // if the target sequence‘s length shorter than minLevel we break the loop. // int minLevel = INT_MAX; while (!paths.empty()) { vector<string> path = paths.front(); paths.pop(); if (path.size() > level) { for (string s : visited) wordList_.erase(s); visited.clear(); // if (path.size() > minLevel) { // break; // } level = path.size(); } string last = path.back(); for (int i = 0; i < last.length(); ++i) { string last_ = last; for (char c = ‘a‘; c <= ‘z‘; ++c) { last_[i] = c; if (wordList_.count(last_)) { vector<string> newpath = path; newpath.push_back(last_); visited.insert(last_); if (last_ == endWord) { minLevel = level; ans.push_back(newpath); } else { paths.push(newpath); } } } } } return ans; } };
Analysis:
https://leetcode.com/problems/word-ladder-ii/discuss/40434/C%2B%2B-solution-using-standard-BFS-method-no-DFS-or-backtracking
标签:from ems tran case path target class size max
原文地址:https://www.cnblogs.com/ruruozhenhao/p/10352397.html