【second】Word Ladder

BFS

    int ladderLength(string start, string end, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len = 1;
        
        unordered_set<string> strs;
        
        queue<string> q;
        q.push(start);
        strs.insert(start);
        int cnt = 1;
        int next_cnt;
        while(!q.empty())
        {
            next_cnt = 0;
            for(int k=0;k<cnt;k++)
            {
                string s = q.front();
                q.pop();
                if(s==end)
                    return len;
                for(int i=0;i<s.size();i++)
                {
                    for(int j=0;j<26;j++)
                    {
                        char c = s[i];
                        s[i] = 'a'+j;
                        if(dict.find(s)!=dict.end()&&strs.find(s)==strs.end())
                        {
                            strs.insert(s);
                            q.push(s);
                            ++next_cnt;
                        }
                        s[i] = c;
                    }
                } 
            }
            
            ++len;
            cnt = next_cnt;
        }
        
        return 0;
        
    }

  

posted @ 2013-10-23 22:57  summer_zhou  阅读(173)  评论(0编辑  收藏  举报