class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict)
{
if(beginWord.size()!=endWord.size())
return 0;
if(beginWord.empty()||endWord.empty())
return 0;
queue<string> q;
q.push(beginWord);
int level = 1;
int count = 1;
unordered_map<string,bool>visited;
while(!q.empty())
{
string temp = q.front();
q.pop();
count--;
for(int i = 0; i < temp.size(); i++)
{
string tmp = temp;
for(char j='a'; j<='z'; j++)
{
if(tmp[i]==j)
continue;
tmp[i] = j;
if(tmp==endWord)
return level+1;
if(wordDict.count(tmp)&&!visited[tmp])
{
q.push(tmp);
visited[tmp]=true;
}
}
}
if(count==0)
{
count = q.size();
level++;
}
}
return 0;
}
};
Word Ladder
最新推荐文章于 2022-04-25 01:07:40 发布