knakul853

Untitled

Jun 9th, 2020
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
  4.        
  5.        int n = (int)wordList.size();
  6.        
  7.         if( !n ) return 0;
  8.        
  9.         unordered_set<string>st;
  10.         unordered_map<string, int>mp;
  11.         mp[beginWord] = 1;
  12.        
  13.         for( string s: wordList )
  14.         {
  15.             st.insert(s);
  16.         }
  17.        
  18.         queue<string>q;
  19.         q.push(beginWord);
  20.        
  21.         int depth = 0;
  22.        
  23.         while( !q.empty() )
  24.         {
  25.              depth++;
  26.             int sz = q.size();
  27.            
  28.             for( int i=0;i<sz;i++)
  29.             {
  30.                 string word = q.front(); q.pop();
  31.                
  32.                 if( word == endWord ) return depth;
  33.                
  34.                 int m = (int)word.size();
  35.                 for(int j=0; j<m; j++)
  36.                 {
  37.                     char temp = word[j];
  38.                    
  39.                     for( char c = 'a'; c<='z'; c++)
  40.                     {
  41.                         word[j] = c;
  42.                         if(st.find(word) == st.end() || mp[word])
  43.                         {
  44.                             continue;
  45.                         }
  46.                         q.push(word);
  47.                         mp[word] = 1;
  48.                     }
  49.                    
  50.                     word[j] = temp;
  51.                 }
  52.                
  53.  
  54.                
  55.             }
  56.            
  57.         }
  58.        
  59.        
  60.        
  61.         return 0;
  62.        
  63.     }
  64. };
Add Comment
Please, Sign In to add comment