Skip to content

Instantly share code, notes, and snippets.

@yzchen
Created August 19, 2019 17:38
Show Gist options
  • Save yzchen/c38ca1ec3bd4265e202f2d04d0e362aa to your computer and use it in GitHub Desktop.
Save yzchen/c38ca1ec3bd4265e202f2d04d0e362aa to your computer and use it in GitHub Desktop.
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;
}
};
@yzchen
Copy link
Author

yzchen commented Aug 19, 2019

Time Limit Exceeded. 30/40 cases passed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment