forked from tanyarajhans/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 142 ms (68.61%), Space: 13.9 MB (70.59%) - LeetHub
- Loading branch information
1 parent
cb05de9
commit 5b62b6a
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
class Solution { | ||
public: | ||
int ladderLength(string beginWord, string endWord, vector<string>& wordList) { | ||
unordered_set<string> myset; | ||
bool isPresent = false; //Checks if endWord is present in Dict | ||
//Insert all words from Dict in myset | ||
for(auto word: wordList) | ||
{ | ||
if(endWord.compare(word)==0) | ||
isPresent = true; | ||
myset.insert(word); //Insert word in Dict | ||
} | ||
if(isPresent==false) //endWord is not present in Dict | ||
return 0; | ||
|
||
queue<string> q; | ||
q.push(beginWord); | ||
int depth = 0; | ||
|
||
while(!q.empty()) | ||
{ | ||
depth+=1; | ||
int lsize = q.size(); //No of elements at a level | ||
while(lsize--) | ||
{ | ||
string curr = q.front(); | ||
q.pop(); | ||
//check for all possible 1 depth words | ||
for(int i=0;i<curr.length();++i) //For each index | ||
{ | ||
string temp = curr; | ||
for(char c='a';c<='z';++c) //Try all possible chars | ||
{ | ||
temp[i] = c; | ||
if(curr.compare(temp)==0) | ||
continue; //Skip the same word | ||
if(temp.compare(endWord)==0) | ||
return depth+1; //endWord found | ||
if(myset.find(temp)!=myset.end()) | ||
{ | ||
q.push(temp); | ||
myset.erase(temp); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
return 0; | ||
} | ||
}; |