活跃农民
- 积分
- 573
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-8-17
- 最后登录
- 1970-1-1
|
解释一下. 直接把单词从词典移除这个想法很妙. 因为当路径长度增加时, 说明当前层和之前层的所有单词或者被遍历过,或者已经在队列里,所以可以移除.
楼主的代码声明了min_level但好像没有用到, 应该可以优化一下. 而且移除单词的时候,也可以同时从visited里移除,节省遍历次数.
AC实现:
- // BFS,
- // Whenever path length increases, means all the words in previous as well as current level has been visited and added to queue
- // So we can remove them from the word list to avoid visit again.
- // Keep appending words to the path, till the queue is empty.
- vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
- unordered_set<string> dict;
- for(size_t i = 0; i < wordList.size(); i++) dict.emplace(wordList[i]);
- unordered_set<string> visited;
- queue<vector<string>> q;
- vector<vector<string>> ans;
- size_t cur_len = 1, min_len = INT_MAX;
- q.emplace(vector<string>{beginWord});
- while(cur_len <= min_len && !q.empty()){
- vector<string> path = q.front(); q.pop();
- if(path.size() > cur_len){
- for(auto it = visited.begin(); it != visited.end();){
- dict.erase(*it);
- it = visited.erase(it);
- }
- cur_len = path.size();
- }
- string w = path.back();
- for(size_t i = 0; i < w.size(); i++){
- char c = w[i];
- for(char new_c = 'a'; new_c <= 'z'; new_c++){
- if(new_c == c) continue;
- w[i] = new_c;
- if(dict.count(w)){
- visited.emplace(w);
- vector<string> candidate = path;
- candidate.emplace_back(w);
- if(w == endWord){
- ans.emplace_back(candidate);
- min_len = min(min_len, candidate.size());
- }else{
- q.emplace(candidate);
- }
- }
- }
- w[i] = c;
- }
- }
- return ans;
- }
复制代码 |
|