Ejemplo n.º 1
0
    vector<vector<string> > findLadders0(string start, string end, unordered_set<string> &dict) {

        dict.insert(start);

        StringVectorQ q;
        q.push_back( StringVectorPtr(new StringVector(1, start)) );
        const int L = end.size();
        StringVectorQ result;
        StringSet visitedS = {start};
        while( !q.empty() ) {
            StringVectorPtr pv = q.front();
            q.pop_front();
            if( pv->size() > shortest )
                continue;
            string s = pv->back();
            for(int i=0; i<L; ++i) {
                string newStr = s;
                char ch = s[i];
                do {
                    ch++;
                    if( ch > 'z') ch = 'a';
                    if( ch == s[i]) break;

                    newStr[i] = ch;
                    if( newStr == end ) {  // found it
                        StringVectorPtr newV(new StringVector(*pv));
                        newV->push_back(newStr);
                        result.push_back(newV);
                        if( newV->size() < shortest)
                            shortest = newV->size();
                    } if( dict.end() != dict.find(newStr) && std::find(pv->begin(), pv->end(), newStr) == pv->end() ) {  // continue with next search
                        StringVectorPtr newV(new StringVector(*pv));
                        newV->push_back(newStr);
                        visitedS.insert(newStr);
                        q.push_back(newV);
                    }
                }while(true);
            }
        }
        struct Smaller{
            int x;
            Smaller(int a):x(a){}
            bool operator()(StringVectorPtr& v) {
                return v->size() < x;
            }
        };

        StringVectorVector vv;
//        std::copy_if(result.begin(), result.end(), std::back_inserter(vv), Smaller(shortest));
        for(StringVectorQ::iterator it=result.begin(); it!=result.end(); ++it) {
            if( (**it).size() <= shortest )
                vv.push_back(std::move(**it));
        }
        return std::move(vv);
    }