leetcode@ [127] Word Ladder (BFS / Graph)

时间:2021-12-06 13:43:50

https://leetcode.com/problems/word-ladder/

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:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.
class node {
public:
string word;
int lv;
node(string s, int v): word(s), lv(v) {}
}; class Solution {
public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
int n = wordList.size(); if(!n) return ;
bool flag = false;
if(wordList.find(endWord) != wordList.end()) flag = true;
wordList.insert(endWord); queue<node> st;
st.push(node(beginWord, )); while(!st.empty()) {
node top = st.front();
st.pop();
int cur_lv = top.lv;
string cur_word = top.word; if(cur_word.compare(endWord) == ) return flag? cur_lv+: cur_lv;
unordered_set<string>::iterator p = wordList.begin(); for(int i=; i<cur_word.length(); ++i) {
for(char c = 'a'; c <= 'z'; ++c) {
char tmp = cur_word[i];
if(cur_word[i] != c) cur_word[i] = c;
if(wordList.find(cur_word) != wordList.end()) {
st.push(node(cur_word, cur_lv+));
wordList.erase(wordList.find(cur_word));
}
cur_word[i] = tmp;
}
}
} return ;
}
};