leetcode[126]Word Ladder II
2015-02-09 13:11
417 查看
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start =
end =
dict =
Return
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start =
"hit"
end =
"cog"
dict =
["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
class Solution { public: void dfs(vector<vector<string>> &res,vector<string> str,unordered_map<string,vector<string>> &father,string start, string now) { if(now==start) { str.push_back(now); res.push_back(str); reverse(res.back().begin(),res.back().end()); return; } for(const auto &x : father[now]) { str.push_back(now); dfs(res,str,father,start,x); str.pop_back(); } } vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string>> res; if(start==end)return res; unordered_set<string> curr,next; unordered_set<string> all; unordered_map<string,vector<string>> father; bool found=false; curr.insert(start); while(!curr.empty()&&!found) { for(const auto &x : curr) { all.insert(x); } for(const auto &x : curr) { for(int i=0;i<x.length();i++) { for(char j='a';j<='z';j++) { if(x[i]==char(j))continue; string tx=x; tx[i]=char(j); if(tx==end)found=true; if(dict.find(tx)!=dict.end()&&all.find(tx)==all.end()) { next.insert(tx); father[tx].push_back(x); } } } } curr.clear(); swap(curr,next); } vector<string> str; dfs(res,str,father,start,end); } };
相关文章推荐
- [Leetcode 126 & 127, hard & medium] Word Ladder II & I
- [leetcode] 126.Word Ladder II
- leetcode 126 Word Ladder II
- leetcode 126. Word Ladder II
- LeetCode 126 Word Ladder II
- leetcode题解-126. Word Ladder II
- LeetCode 126. Word Ladder II
- LeetCode 126 Word Ladder II
- Leetcode(W5):126. Word Ladder II
- Leetcode 127. Word Ladder I & 126. Word Ladder II
- Leetcode 126. Word Ladder II[hard]
- Leetcode 126. Word Ladder II
- leetcode 126. Word Ladder II
- LeetCode 126. Word Ladder II(单词梯子)
- [Leetcode 12] 126 Word Ladder II TO_BE_ADDED
- [leetcode] 126 Word Ladder ii bfs dfs
- leetcode_c++:Word Ladder II(126)
- Leetcode 126. Word Ladder II
- Leetcode 126. Word Ladder II
- [LeetCode] 126. Word Ladder II 词语阶梯 II