Created
August 19, 2019 17:38
-
-
Save yzchen/c38ca1ec3bd4265e202f2d04d0e362aa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Solution { | |
int dist(string &s, string &t){ | |
int cnt=0; | |
for(int i=0;i<s.size();i++) | |
if(s[i]!=t[i]) | |
cnt++; | |
return cnt; | |
} | |
public: | |
int ladderLength(string beginWord, string endWord, vector<string>& wordList) { | |
if(wordList.empty()) | |
return 0; | |
queue<string> q; | |
int level=0; | |
unordered_set<string> s(wordList.begin(),wordList.end()); | |
if(s.count(endWord)==0) | |
return 0; | |
q.push(beginWord); | |
while(!q.empty()){ | |
int sz=q.size(); | |
level++; | |
while(sz--){ | |
string cur=q.front(); | |
q.pop(); | |
if(s.count(cur)>0) | |
s.erase(cur); | |
if(cur.compare(endWord)==0) | |
return level; | |
for(auto candi:s){ | |
if(dist(candi,cur)==1) | |
q.push(candi); | |
} | |
} | |
} | |
return 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Time Limit Exceeded. 30/40 cases passed.