clear and short c++ BFS use two deque


  • 0
    H
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
    	int res = 1;
    	deque<string> candidate;
    	deque<string> cur;
    	cur.push_back(beginWord);
    	wordList.erase(beginWord);
    	string temp;
    	while (!cur.empty()) {
    		while (!cur.empty()) {
    			beginWord = cur.front();
    			cur.pop_front();
    			for (int i = 0;i<endWord.size();i++) {
    				temp = beginWord;
    				for (int j = 0;j<26;j++) {
    					temp[i] = 'a' + j;
    					if (temp == endWord) return res+1;
    					if (temp != beginWord&&wordList.find(temp) != wordList.end()) {
    						candidate.push_front(temp);
    						wordList.erase(temp);
    					}
    				}
    			}
    		}
    		swap(cur, candidate);
    		res++;
    	}
    	return 0;
    }
    

Log in to reply
 

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