aboutsummaryrefslogtreecommitdiff
path: root/word_ladder.cpp
blob: dfe6b00a6b887d450773b8dc23fa92e7dd20a1de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "leetcode.h"

class Solution {
public:
  int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
    unordered_set<string> dict(wordList.begin(), wordList.end());
    queue<string> q;
    q.push(beginWord);
    int ladder = 1;
    while (!q.empty()) {
      int n = q.size(); //
      for (int i = 0; i < n; i++) {
        string word = q.front();
        q.pop();
        if (word == endWord)
          return ladder;
        dict.erase(word);
        for (int j = 0; j < word.size(); j++) {
          char c = word[j];
          for (int k = 0; k < 26; k++) {
            word[j] = 'a' + k;
            if (dict.find(word) != dict.end())
              q.push(word);
          }
          word[j] = c;
        }
      }
      ladder++;
    }
    return 0;
  }
};

int main() {
  Solution obj;
  string beginWord = "hit", endWord = "cog";
  vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"};
  cout << obj.ladderLength(beginWord, endWord, wordList);
}