LeetCode 127. Word Ladder

#include <string>
#include <unordered_set>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

/*
  Given two words (beginWord and endWord), and a dictionary's word list.
  find the length of shortest transformation sequence from beginWord to
  endWord, such that:
  1: only one letter can be changed at a time.
  2: Each intermediate word must exist in the word list.
  For example:
  Given, beginWord = "hit", endWord = "cog"
  WordList = ["hot", "dot", "dog", "lot", "log"]
  As one shortest transformation is "hit"-> "hot"->"dot"->"dog"->"cog"
  return its length 5.

  Note:
  1: Return 0 if there is no such transformation sequence.
  2: all words have the same length.
  3: All words contain only lowercase alphabetic characters.
*/

// BFS 
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
  struct wordAndDistance {
    string word;
    int distance;
  };
  queue<wordAndDistance> q;
  wordList.erase(beginWord);
  q.emplace(wordAndDistance{beginWord, 1});
  while(!q.empty()) {
    wordAndDistance f(q.front());
    if(f.word == endWord) return f.distance;

    string str = f.word;
    for(int i = 0; i < str.size(); ++i) {
      for(int j = 0; j < 26; ++j) {
        str[i] = 'a' + j;
        auto it(wordList.find(str));
        if(it != wordList.end()) {
          wordList.erase(it);
          q.emplace(wordAndDistance{str, f.distance + 1});
        }
      }
      str[i] = f.word[i];
    }
    q.pop();
  }
  return -1;
}

int main(void) {
  string beginWord = "hit";
  string endWord = "cog";
  unordered_set<string> wordList{"hot", "dot", "dog", "lot", "log", "cog", "hit"};
  cout << ladderLength(beginWord, endWord, wordList) << endl;
}
 

你可能感兴趣的:(LeetCode 127. Word Ladder)