Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.0 kB
1
Indexable
Never
class Solution { //same as genetic mutation?
public:
    int ladderLength(string start, string end, vector<string>& bank) {
        unordered_set<string> st{bank.begin(),bank.end()};
        if(!st.count(end)) return 0;
        queue<string> q;
        q.push(start);
        int count=0;
        while(!q.empty()){
            int s=q.size();
            while(s--){
                string f=q.front();
                q.pop();
                if(f==end) return count +1;
                st.erase(f); // we have visited this word ,dont visit it again

                //string d=f; //too many computations
                for(int i=0;i<f.size();i++){
                    char org=f[i];

                    for(char c='a' ; c<='z';c++){
                        f[i]=c;
                        if(st.count(f)) q.push(f);
                    }

                    f[i]=org; //backtracking
                }
            }
            count++;
        }
        return 0;  
    }
};