Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
- unordered_map<string,int> map;
- for(auto x:wordList) map[x]=0;
- queue<vector<string>> q;
- vector<vector<string>> ans;
- q.push({beginWord});
- map[beginWord]=1;
- //1 means visited
- while(!q.empty()) {
- auto temp = q.front();
- q.pop();
- string word = temp.back();
- if(word==endWord) {
- map[word]=0;
- ans.push_back(temp);
- continue;
- }
- for(int i=0;i<word.length();i++) {
- char x = word[i];
- for(int c='a';c<='z';c++) {
- word[i]=c;
- if (map.find(word)!=map.end() && map.find(word)->second!=1) {
- map[word]=1;
- vector<string> list = temp;
- list.push_back(word);
- q.push({list});
- }
- }
- word[i]=x;
- }
- map[word]=0;
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement