LeetCode OJ - Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

  1. Only one letter can be changed at a time
  2. 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.

分析:一道給力的題,有人說是五星題。採用BFS遍歷,並使用vector<string, vector<string> >鄰接表來構建圖模型,最後使用DFS深度搜索圖來得到所有結果。如果遍歷圖有重複元素,可以使用一個標記爲來記錄visited。


class Solution {
    vector<vector<string> > ret;
    string END;
public:
    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
        END = end;
        
        queue<string> que, next;
        que.push(start);
        dict.erase(start);
        
        unordered_set<string> del;
        del.insert(start);

        unordered_map<string, vector<string> > path;
        
        bool found = false;
        while(!que.empty()) {
            for(auto x : del) dict.erase(x);
            del.clear();

            while(!que.empty()) {
                string x = que.front();  que.pop();
                
                //根據cur查找,並push到next隊列
                for(int i = 0; i < x.size(); i++) {
                    string word = x;     
                    for(char ch = 'a'; ch <= 'z'; ch++) {
                        
                        if(word[i] == ch) continue;
                        word[i] = ch;
                        
                        
                        //找到可達字符集合,記錄到path中
                        if(dict.count(word)) {
                            if(word == end) found = true;
                            if(!del.count(word))next.push(word);
                            del.insert(word);
                            path[x].push_back(word); 
                        }
                    }
                }
            }
            
            if(found) break;
            swap(que, next);

        }
        
        vector<string> item;
        item.push_back(start);
        DFS(path, start, item);
        return ret;
    }
private:    
    void DFS(unordered_map<string, vector<string> > &path, string last, vector<string> &item) {
        if(last == END) {
            ret.push_back(item);
            return ;
        }
        
        for(int i = 0; i < path[last].size(); i++) {
            item.push_back(path[last][i]);
            DFS(path, path[last][i], item);
            item.pop_back();
        } 
    
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章