Word Ladder

来源:互联网 发布:拉杆箱推荐 知乎 编辑:程序博客网 时间:2024/04/30 01:30

BFS:

class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        // Start typing your C/C++ solution below        // DO NOT write int main() function                if (start==end) return 1;        int level=1, width1=0, width2=1;        queue<string> q;        unordered_set<string> res;        q.push(start);                while (!q.empty()) {            string cur=q.front();            q.pop();            width2--;                        for (int i=0; i<cur.size(); i++) {                for (int j=0; j<26; j++) {                    string next=cur;                    next[i]=j+'a';                                        if (next==end) {                        return level+1;                    }                    if (dict.find(next)!=dict.end() && res.find(next)==res.end()) {                        res.insert(next);                        width1++;                        q.push(next);                    }                }                            }            if (width2==0) {                width2=width1;                width1=0;                level++;            }        }        return 0;    }};


原创粉丝点击