1
// For approach: ref: https://www.youtube.com/watch?v=ZVJ3asMoZ18&t=0s5
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {6
// 1. Create a set and insert all wordList to the set to have8
unordered_set<string> wordSet;9
bool isEndWordPresent = false;10
for (string s : wordList) {11
// Check if the destination string even present in the wordList12
// If not then there is no point in even trying to find the13
// route from source string to destination string14
if (!isEndWordPresent && s.compare(endWord) == 0) {15
isEndWordPresent = true;20
// 2. If endWord is not present in the wordList return21
if (!isEndWordPresent) {25
// 3. Create a queue for BST insert the elements of currentlevel to the26
// queue currentLevel is defined as all the strings that can be reached from27
// all the strings of the previous string by just replacing one character28
// and the one-char-replaced-string is present in the wordSet / wordList31
int level = 0; // every time all the strings at this level are processed34
// 4. Loop through all the elements in the queue37
int numStringsInCurLevel = q.size();38
// loop through all the strings in this current level39
// and find out if destination can be reached before40
// jumping to the next level of strings added to the queue41
while (numStringsInCurLevel--) {42
string curStr = q.front();45
for (int i = 0; i < curStr.length(); i++) {46
string tempStr = curStr;47
// Now check if swappin one char in the curStr will48
// lead to any string in the wordSet49
for (char c = 'a'; c <= 'z'; c++) {51
if (tempStr.compare(curStr) == 0) {52
// Ignore the same string55
// Check if we reached the destination56
if (tempStr.compare(endWord) == 0) {59
if (wordSet.find(tempStr) != wordSet.end()) {60
// this string is in the set so add it to the queue61
// and remove it from the set63
wordSet.erase(tempStr);70
// If we are here then we couldn't reach destination71
// even though the destination string is present in the wordList72
// there is no path from source to destination for the given rules