Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
- int n = (int)wordList.size();
- if( !n ) return 0;
- unordered_set<string>st;
- unordered_map<string, int>mp;
- mp[beginWord] = 1;
- for( string s: wordList )
- {
- st.insert(s);
- }
- queue<string>q;
- q.push(beginWord);
- int depth = 0;
- while( !q.empty() )
- {
- depth++;
- int sz = q.size();
- for( int i=0;i<sz;i++)
- {
- string word = q.front(); q.pop();
- if( word == endWord ) return depth;
- int m = (int)word.size();
- for(int j=0; j<m; j++)
- {
- char temp = word[j];
- for( char c = 'a'; c<='z'; c++)
- {
- word[j] = c;
- if(st.find(word) == st.end() || mp[word])
- {
- continue;
- }
- q.push(word);
- mp[word] = 1;
- }
- word[j] = temp;
- }
- }
- }
- return 0;
- }
- };
Add Comment
Please, Sign In to add comment