起点和终点一起进行广度优先遍历
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_map<string, int>hash, hash2;
queue<string>que, que2;
int n = beginWord.size();
for (vector<string>::iterator it = wordList.begin(); it != wordList.end(); ++it)
{
hash[*it] = INT_MAX;
hash2[*it] = INT_MAX;
}
hash[beginWord] = 1;
if(!hash.count(endWord)) return 0;
hash2[endWord] = 1;
hash2[beginWord] = INT_MAX;
que.push(beginWord);
que2.push(endWord);
while (!que.empty() && !que2.empty())
{
string s = que.front();
string s2 = que2.front();
que2.pop();
que.pop();
for (int i = 0; i<n; ++i)
{
string ss = s;
for (char x = 'a'; x <= 'z'; ++x)
{
ss[i] = x;
if (hash2.count(ss) && hash2[ss]<INT_MAX)
{
int a = hash2[ss];
int b = hash[s];
return hash2[ss] + hash[s];
}
else if (hash.count(ss)) {
if (hash[ss]>(hash[s] + 1))
{
hash[ss] = hash[s] + 1;
if (ss == endWord)
{
return hash[ss];
}
que.push(ss);
}
}
}
}
for (int i = 0; i<n; ++i)
{
string ss = s2;
for (char x = 'a'; x <= 'z'; ++x)
{
ss[i] = x;
if (hash.count(ss) && hash[ss]<INT_MAX)
{
int ret = hash[ss] + hash2[s2];
int a = hash[ss];
int b = hash2[s2];
return ret;
}
else if (hash2.count(ss)) {
if (hash2[ss]>(hash2[s2] + 1))
{
hash2[ss] = hash2[s2] + 1;
if (ss == beginWord)
{
return hash2[ss];
}
que2.push(ss);
}
}
}
}
}
return 0;
}
};