Wednesday, December 3, 2014

Word Ladder

    int ladderLength(string start, string end, unordered_set<string> &dict) {
        int ret = 0;
        if (start == end)
            return ret;
   
        unordered_set<string> added;
        queue<string> que;
        int lev1 = 1;
        int lev2 = 0;
        que.push(start);
        added.insert(start);
   
        while (!que.empty()) {
            string s = que.front();
            que.pop();
            --lev1;
   
            for (int i = 0; i < s.length(); ++i) {
                char before=s[i];
                for (int j = 0; j < 26; ++j) {
                    s[i] = 'a' + j;
                    if (s == end)
                        return ret + 2;
                    if (dict.find(s) != dict.end()
                        && added.find(s) == added.end()) {
                        que.push(s);
                        added.insert(s);
                        ++lev2;
                    }
                }
                s[i]=before;
            }
   
            if (lev1 == 0) {
                ++ret;
                lev1 = lev2;
                lev2 = 0;
            }
        }
   
        return 0;
    }

//another flavor, by annikim
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        queue<pair<string,int>> que;
        que.push(make_pair(start,1));
        while(!que.empty()){
            pair<string,int> front=que.front();que.pop();
            string word=front.first;
            for(int i=0;i<word.length();i++){
                char before=word[i];
                for(char c='a';c<='z';c++){
                    word[i]=c;
                    if(word==end) return front.second+1;
                    if(dict.find(word)!=dict.end()){
                        que.push(make_pair(word,front.second+1));
                        dict.erase(word);
                    }
                }
                word[i]=before;
            }
        }
        return 0;
    }

No comments:

Post a Comment