Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters

思路:这道题使用BFS(广度优先搜索),使用队列作为辅助空间,将遍历得到满足条件的字符串放入path中,并且遍历到的字符串在dict出现过,我们也要删除dict中该字符串,防止以后再遍历到此字符串。

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        if(start.size()!=end.size())
            return 0;
        if(start.empty()||end.empty())
            return 0;
        if(dict.size()==0)
            return 0;
        queue<string> path;
        path.push(start);
        int level=1;
        int count=1;
        dict.erase(start);
        while(dict.size()>0 && !path.empty())
        {
            string s=path.front();
            path.pop();
            count--;
            for(int i=0;i<s.size();i++)
            {
                string temp(s);
                for(char ch='a';ch<='z';ch++)
                {
                    if(temp[i]==ch)
                        continue;
                    temp[i]=ch;
                    if(temp==end)
                        return level+1;
                    if(dict.find(temp)!=dict.end())
                    {
                        path.push(temp);
                    }
                    dict.erase(temp);
                }
            }
            if(count==0)
            {
                count=path.size();
                level++;
            }
        }
        return 0;
    }
};
原文地址:https://www.cnblogs.com/awy-blog/p/3819326.html