Skip to content
Discussion options

You must be logged in to vote

class Solution {
public:
int ladderLength(string beginWord, string endWord, vector& wordList) {
unordered_set st(wordList.begin(), wordList.end());
if (!st.count(endWord)) return 0;

    queue<pair<string,int>> q;
    q.push({beginWord, 1});

    while (!q.empty()) {
        auto [word, steps] = q.front();
        q.pop();

        for (int i = 0; i < word.size(); i++) {
            string temp = word;
            for (char ch = 'a'; ch <= 'z'; ch++) {
                temp[i] = ch;

                if (st.count(temp)) {
                    q.push({temp, steps + 1});
                    st.erase(temp); // mark visited
                }
            }
        }
    }
    return 0;
}

};

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by mrenemy999-os
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Discussions GitHub Discussions is a collaborative communication feature Question Ask and answer questions about GitHub features and usage source:ui Discussions created via Community GitHub templates
3 participants