LC 127. Word Ladder (two end bfs)
Posted feiief
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 127. Word Ladder (two end bfs)相关的知识,希望对你有一定的参考价值。
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> words; for(auto &s:wordList){ words.insert(s); } if(words.find(endWord)==words.end()) return 0; unordered_set<string> beginSet; unordered_set<string> endSet; beginSet.insert(beginWord); endSet.insert(endWord); unordered_set<string> visited; visited.insert(beginWord); visited.insert(endWord); int level=1; while(!beginSet.empty() && !endSet.empty()){ if(beginSet.size()>endSet.size()){ auto tmp=beginSet; beginSet=endSet; endSet=tmp; } unordered_set<string> tmp; for(auto s:beginSet){ for(int i=0;i<s.size();++i){ char bk=s[i]; for(char c=‘a‘;c<=‘z‘;++c){ if(c==bk) continue; s[i]=c; if(endSet.find(s)!=endSet.end()) return level+1; if(visited.find(s)==visited.end() && words.find(s)!=words.end()){ visited.insert(s); tmp.insert(s); } } s[i]=bk; } } beginSet=tmp; ++level; } return 0; } };
以上是关于LC 127. Word Ladder (two end bfs)的主要内容,如果未能解决你的问题,请参考以下文章