20190421-Leetcode-127.单词接龙

Leetcode-127.单词接龙

给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord到 endWord 的最短转换序列的长度。转换需遵循如下规则:
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
输出: 5
解释: 一个最短转换序列是 “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
返回它的长度 5。

示例 2:
输入:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,“dot”,“dog”,“lot”,“log”]
输出: 0
解释: endWord “cog” 不在字典中,所以无法进行转换。

思路
构建一个图网络,unordered_map<string, vector> graph,把wordList中的所有单词作为结点,然后,把每个节点经过1次变换得到的单词存入其对应的vector中。
用图广度优先搜索遍历搜索,用queue<string, int> queue实现; 并且记录每个单词的深度,即变换的次数。若节点的其他相邻结点没有遍历过则存入队列,依次出队,如果是所遍历的结点,则输出该节点的层数,若不是队列为空了,则返回0;

代码

class Solution {
public:
    bool connect(string &Word1, string &Word2){
        int count = 0;
        for(int i = 0; i < Word2.size(); i++){
            if(Word1[i] != Word2[i]){
                count++;
            }
        }
        return count == 1;
    }
    void construct_graph(string &beginWord, unordered_map<string, vector<string> > &graph, vector<string>& wordList){
        wordList.push_back(beginWord);
        for(int i = 0; i < wordList.size(); i++){
            graph[wordList[i]] = vector<string>();
        }
        for(int i = 0; i < wordList.size(); i++){
            for(int j = i + 1; j < wordList.size(); j++){
                if(connect(wordList[i], wordList[j])){
                    graph[wordList[i]].push_back(wordList[j]);
                    graph[wordList[j]].push_back(wordList[i]);
                }
            }
        }
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_map<string, vector<string> > graph;
        construct_graph(beginWord, graph, wordList);
        queue<pair<string, int>> que;
        unordered_map<string, int> is;
        que.push(make_pair(beginWord, 1));
        is[beginWord] = 1;
        while(!que.empty()){
            string tempWord = que.front().first;
            int tempDeep = que.front().second;
            que.pop();
            if(tempWord == endWord){
                return tempDeep;
            }
            for(int i = 0; i < graph[tempWord].size(); i++){
                if(is.find(graph[tempWord][i]) == is.end()){
                    que.push(make_pair(graph[tempWord][i], tempDeep + 1));
                    is[graph[tempWord][i]] = 1;
                }
            }
        }
        return 0;
    } 
};

猜你喜欢

转载自blog.csdn.net/study_deep/article/details/89917084