• `````` class Solution {
public:

void addNextWord(string word, unordered_set<string>& wordDict, queue<string>& toVisit)
{
wordDict.erase(word);                             //erase every visited node

for(int p=0; p<(int)word.length(); p++)
{
char letter = word[p];
for(int i=0; i<26; i++)
{
word[p] = 'a' + i;                        //test for the word neighbours by replacing each of its alphabets

if(wordDict.find(word)!=wordDict.end())   //if new word being formed by replacing p with each of the 26 alphabets is found
{
toVisit.push(word);                             //add it to the queue
wordDict.erase(word);                           //delete it from dictionary
}
}
word[p] = letter;                            //restore the word back
}
}

int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict)
{
wordDict.insert(endWord);                   //add endword to the dictionary

queue<string> toVisit;                      //make a queue for BFS
int dist = 2;
while(!toVisit.empty())                     //while queue not empty
{
int num = toVisit.size();
for(int i=0; i<num; i++)   //traverse all nodes of a level of BFS tree so formed
{
string word = toVisit.front();
toVisit.pop();                      //pop the front word

if(word == endWord)                 //if it is equal to endword, we have reached the end
return dist;
}

dist++;
}
}

};
``````

Here, in the ladderLength() function, in the while loop, I am storing the length of the queue in an interger variable num, my solution is getting accepted.

``````        int num = toVisit.size();
for(int i=0; i<num; i++)                                 //no problem
{
......
}
``````

But when, I combine this in the while loop and avoid taking an extra variable, I am getting error.

``````        for(int i=0; i<toVisit.size(); i++)                     //"a", "c", ["a", "b", "c"]  : test case fails
{
......
}
``````