How to handle the failure case(-1) ?


  • 0
    K

    I am able to solve when the target could be achieved, but could not when the target is impossible with the following deadends?. Can anyone help me on this?

    class Solution {
    public:
        int openLock(vector<string>& deadends, string target) {
            int changes = 1;
            queue<string> toBeVisited;
            addNextCombinations("0000", deadends, toBeVisited);
            while(!toBeVisited.empty()) {
                int queuelen = toBeVisited.size();
                for (int i = 0; i < queuelen; i++) {
                    string combination = toBeVisited.front();
                    toBeVisited.pop();
                    // cout << combination << endl;
                    if (combination == target) return changes;
                    addNextCombinations(combination, deadends, toBeVisited);
                }
                changes++;
            }            
        }
    private:
        void addNextCombinations(string curr, vector<string>& deadends, queue<string>& toBeVisited) {  
            for (int i = 0; i < (int)curr.length(); i++) {
                char temp = curr[i];
                curr[i] = curr [i] + 1;
                if(std::find(deadends.begin(), deadends.end(), curr) == deadends.end()) {
                    toBeVisited.push(curr);
                }
                curr[i] = temp;
                temp = curr[i];
                if(curr[i] == '0') {            
                    curr[i] = '9';
                } else {
                    curr[i] = curr [i] - 1;
                }
                if(std::find(deadends.begin(), deadends.end(), curr) == deadends.end()) {
                    toBeVisited.push(curr);
                }
                curr[i] = temp;
    
            } 
        }     
    };
    

Log in to reply
 

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