# 双向BFS及优化

``````class Solution {
public:
int BFS(bool dir, queue<string>& qu, unordered_set<string>& wordList){
queue<string> next;
while(!qu.empty()){
string cur = qu.front();
qu.pop();
int step = dis[dir][cur];
++step;
for(int i = 0; i < len; ++i){
char c = cur[i];
for(char j = 'a'; j <= 'z'; ++j){
if(j == c)
continue;
cur[i] = j;
if(wordList.find(cur) != wordList.end() && dis[dir][cur] == INT_MAX){
if(dis[!dir][cur] != INT_MAX)
return dis[!dir][cur] + step + 1;
next.push(cur);
dis[dir][cur] = step;
}
}
cur[i] = c;
}
}
qu = next;
return 0;
}
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
len = beginWord.size();
queue<string> qu1, qu2;
for(unordered_set<string>::iterator it = wordList.begin(); it != wordList.end(); ++it){
dis[0].insert(make_pair(*it, INT_MAX));
dis[1].insert(make_pair(*it, INT_MAX));
}
dis[0][beginWord] = 0, dis[1][endWord] = 0;
qu1.push(beginWord), qu2.push(endWord);
bool dir = false;
while(!qu1.empty() && !qu2.empty()){
int t = BFS(dir, qu1, wordList);
if(t)
return t;
t = BFS(!dir, qu2, wordList);
if(t)
return t;
}
return 0;
}
private:
unordered_map<string, int> dis[2];
int len;
};``````

1.  若X和Y在同一层，则当且仅当从终点搜索时Y位于X前面层，Y才为最优解。设从起点搜索Y的前一个节点为z，由于终点方向从Y所在层，扩展到X所在层，这个过程是连续，所以在这个过程中会首先扩展到z，则z被当做最优解，程序return。如下图所示:

2.  Y位于X的后面，令X和Y相隔i层，则Y为最优解的充分条件为：从终点方向，Y与X的层数之差大于i，记为j。令起点方向上，z是y的前j个节点。那么从终点方向搜索时，z应该不晚于x被搜到。因此也不会错过最优解。如下图所示：

``````class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
queue<string> qu1, qu2;
qu1.push(beginWord);
qu2.push(endWord);
int len = beginWord.size();
unordered_map<string, int> dis[2];
for(unordered_set<string>::iterator it = wordList.begin(); it != wordList.end(); ++it){
dis[0].insert(make_pair(*it, INT_MAX));
dis[1].insert(make_pair(*it, INT_MAX));
}
dis[0][beginWord] = 0, dis[1][endWord] = 0;
bool dir = false;
while(!qu1.empty()){
queue<string> layer;
while(!qu1.empty()){
string cur = qu1.front();
qu1.pop();
int step = dis[dir][cur];
++step;
for(int i = 0; i < len; ++i){
char c = cur[i];
for(char j = 'a'; j <= 'z'; ++j){
if(j == c)
continue;
cur[i] = j;
if(wordList.find(cur) != wordList.end() && dis[dir][cur] == INT_MAX){
if(dis[!dir][cur] != INT_MAX)
return step + dis[!dir][cur] + 1;
layer.push(cur);
dis[dir][cur] = step;
}
}
cur[i] = c;
}
}
if(layer.size() > qu2.size()){
qu1 = qu2;
qu2 = layer;
dir = !dir;
}
else
qu1 = layer;
}
return 0;
}
};``````

原文作者：BFS
原文地址: https://blog.csdn.net/ww32zz/article/details/50755225
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。