Why it keep saying that Time Limit Exceeded?


  • 0
    S

    My code:

     class Solution {
    public:
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        vector<vector<string>> result;
        
        unordered_map<string, bool> dic;
        for(const string &ele : wordList)
            dic[ele] = false;
        
        std::queue<vector<string>> ique;
        int dis = 0;
        int len = beginWord.size();
        
        vector<string> path;
        path.push_back(beginWord);
        
        ique.push(path);
        
        bool bFound = false;
        
        while(!ique.empty())
        {
            vector<string> ipath = ique.front();
            string curr = ipath.back();
            ique.pop();
            dic[ipath.back()] = true;
            
            if(curr == endWord && !bFound)
            {
                dis = ipath.size();
                bFound = true;
            }
            
            if(bFound)
            {
                if(curr == endWord && ipath.size() == dis)
                    result.push_back(ipath);
                continue;
            }
    
            for(int i =0; i< len; ++i)
            {
                char reser = curr[i];
                
                for(char k = 'a'; k<= 'z'; ++k)
                {
                    if(reser == k)
                        continue;
                    curr[i] = k;
                    
                    if(dic.find(curr) != dic.end() && dic[curr] == false)
                    {
                        ipath.push_back(curr);
                        ique.push(ipath);
                        ipath.pop_back();
                    }
                }
                curr[i] = reser;
            }
            
        }
        
        return result;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.