1
+ // Runtime: 290 ms (Top 55.58%) | Memory: 13.9 MB (Top 85.26%)
1
2
// For approach: ref: https://www.youtube.com/watch?v=ZVJ3asMoZ18&t=0s
2
3
3
- class Solution
4
+ class Solution
4
5
{
5
6
public:
6
- int ladderLength (string beginWord, string endWord, vector<string>& wordList)
7
+ int ladderLength (string beginWord, string endWord, vector<string>& wordList)
7
8
{
8
9
// 1. Create a set and insert all wordList to the set to have
9
- // easy search of O(1)
10
+ // easy search of O(1)
10
11
unordered_set<string> wordSet;
11
12
bool isEndWordPresent = false ;
12
13
for (string s:wordList)
@@ -20,34 +21,34 @@ class Solution
20
21
}
21
22
wordSet.insert (s);
22
23
}
23
-
24
+
24
25
// 2. If endWord is not present in the wordList return
25
26
if (!isEndWordPresent)
26
27
{
27
28
return 0 ;
28
29
}
29
-
30
+
30
31
// 3. Create a queue for BST insert the elements of currentlevel to the queue
31
- // currentLevel is defined as all the strings that can be reached from
32
- // all the strings of the previous string by just replacing one character
33
- // and the one-char-replaced-string is present in the wordSet / wordList
32
+ // currentLevel is defined as all the strings that can be reached from
33
+ // all the strings of the previous string by just replacing one character
34
+ // and the one-char-replaced-string is present in the wordSet / wordList
34
35
queue<string> q;
35
36
q.push (beginWord);
36
37
int level = 0 ; // every time all the strings at this level are processed increment it
37
-
38
+
38
39
// 4. Loop through all the elements in the queue
39
40
while (!q.empty ())
40
41
{
41
42
level++;
42
43
int numStringsInCurLevel = q.size ();
43
- // loop through all the strings in this current level
44
+ // loop through all the strings in this current level
44
45
// and find out if destination can be reached before
45
46
// jumping to the next level of strings added to the queue
46
47
while (numStringsInCurLevel--)
47
48
{
48
49
string curStr = q.front ();
49
50
q.pop ();
50
-
51
+
51
52
for (int i=0 ; i<curStr.length (); i++)
52
53
{
53
54
string tempStr = curStr;
@@ -76,8 +77,8 @@ class Solution
76
77
}
77
78
}
78
79
}
79
- }
80
-
80
+ }
81
+
81
82
// If we are here then we couldn't reach destination
82
83
// even though the destination string is present in the wordList
83
84
// there is no path from source to destination for the given rules
0 commit comments