jayati

127. Word Ladder-I

Sep 24th, 2023
918
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
  4.         queue<pair<string,int>> q;
  5.         q.push({beginWord,1});
  6.         unordered_set<string> s(wordList.begin(),wordList.end());
  7.         s.erase(beginWord);
  8.         while(!q.empty())
  9.         {
  10.             string word = q.front().first;
  11.             int steps = q.front().second;
  12.             q.pop();
  13.             if(word==endWord)
  14.             {
  15.                 return steps;
  16.             }
  17.             for(int i=0;i<word.length();i++)
  18.             {
  19.                 char original=word[i];
  20.                 for(char ch='a';ch<='z';ch++)
  21.                 {
  22.                     word[i]=ch;
  23.                     if(s.find(word)!=s.end())
  24.                     {
  25.                         s.erase(word);
  26.                         q.push({word,steps+1});
  27.                     }
  28.                 }
  29.                 word[i]=original;
  30.             }
  31.         }
  32.         return 0;
  33.     }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment