Advertisement
nikunjsoni

127

May 4th, 2021
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
  4.         unordered_map<string, int> m;
  5.         int count = 1;
  6.         for(string word: wordList)
  7.             m[word] = count++;
  8.         if(!m.count(beginWord)) m[beginWord] = count++;
  9.        
  10.         // Create graph.
  11.         vector<vector<int>> graph(count);
  12.         for(auto p: m){
  13.             string word = p.first;
  14.             int wordIdx = p.second;
  15.             for(int i=0; i<word.length(); i++){
  16.                 for(int j=1; j<26; j++){
  17.                     string nextWord = word;
  18.                     nextWord[i] = (nextWord[i]-'a'+j)%26 + 'a';
  19.                     if(m.count(nextWord)){
  20.                         graph[wordIdx].push_back(m[nextWord]);
  21.                     }
  22.                 }
  23.             }
  24.         }
  25.        
  26.         // Do BFS.
  27.         if(!m.count(endWord)) return 0;
  28.         queue<int> q;
  29.         vector<bool> vis(count, false);
  30.         int source = m[beginWord];
  31.         q.push(source); vis[source] = true;
  32.         int ans = 1;
  33.         int dest = m[endWord];
  34.         while(!q.empty()){
  35.             int sz = q.size();
  36.             for(int i=0; i<sz; i++){
  37.                 int curr = q.front(); q.pop();
  38.                 for(int child: graph[curr]){
  39.                     if(child == dest)
  40.                         return ans+1;
  41.                     if(!vis[child]){
  42.                         vis[child] = true;
  43.                         q.push(child);
  44.                     }
  45.                 }
  46.             }
  47.             ans++;
  48.         }
  49.         return 0;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement