clueless coding // TODO: be smarter

LeetCode Word Ladder: CPP Solution



TL;DR Code Solution


int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    queue<string> que;
    que.push(beginWord);
    set<string> dict;
    int len = beginWord.length();

    for (int i = 0; i < wordList.size(); i++) {
        dict.insert(wordList[i]);
    }

    int transformations = 1;
    while (!que.empty()) {
        int size = que.size();
        for (int q = 0; q < size; q++) {
            string current = que.front();
            que.pop();
            if (current == endWord) {
                return transformations;
            }
            for (int i = 0; i < len; i++) {
                char temp = current[i];
                for (int j = 0; j < 26; j++) {
                    current[i] = 'a' + j;
                    if (dict.find(current) != dict.end()) {
                        que.push(current);
                        dict.erase(current);
                    }
                }
                current[i] = temp;
            }
        }
        transformations++;
    }

    return 0;
}