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

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 0;
        bool flag = false;
        if(wordList.find(endWord) != wordList.end())  flag = true;
        wordList.insert(endWord);
        
        queue<node> st;
        st.push(node(beginWord, 0));
        
        while(!st.empty()) {
            node top = st.front();
            st.pop();
            int cur_lv = top.lv; 
            string cur_word = top.word;
            
            if(cur_word.compare(endWord) == 0)  return flag? cur_lv+1: cur_lv;
            unordered_set<string>::iterator p = wordList.begin();
            
            for(int i=0; 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+1));
                        wordList.erase(wordList.find(cur_word));
                    }
                    cur_word[i] = tmp;
                }
            }
        }
        
        return 0;
    }
};
原文地址:https://www.cnblogs.com/fu11211129/p/5278129.html