给定两个字符串和一个字典,从头到尾找到最短变换序列的长度,使得:一次只能改变一个字符每个中间词必须存在于字典中

来源:互联网 发布:赵薇事件的始末 知乎 编辑:程序博客网 时间:2024/06/05 16:10

本题源自LeetCode

------------------------------------------------------------------------------

给定的俩个字串和字典中的串是一张无向图,构造一棵图的树,广度遍历(按层)这棵树,每次改变开始串的一个字符,如果在字典中就入队列,并从字典中删除,防止重复。

int ladderLength(string start, string end, unordered_set<string> &dict) {        int count=1;        unordered_set<string> ret=dict;        queue<string> que;        que.push(start);        while(!que.empty()){            int size=que.size();            //构造树当前层循环            while(size--){                string s=que.front();que.pop();                for(int i=0;i<s.length();i++){                    string word=s;                    for(char j='a';j<='z';j++){                         if(s[i]==j)                            continue;                             s[i]=j;                        if(s==end)                            return count+1;                        if(ret.count(s)>0){                            que.push(s);                            ret.erase(s);                        }                    }                    s=word;  //还原字符串                }            }            //遍历完一层 加 1            count++;        }        return 0;    }


阅读全文
0 0
原创粉丝点击