LeetCode 127. 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:

Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

坎坷过程:

给定开始字符串和结束字符串,以及一个存好的字符串数组,要求每次只能改变一个字母,求出从开始变换到结束所需要的次数。如果字符串数组里面没有结束字符串或者变换不到结束字符串,则返回0。
也不知道自己有多傻,刚开始看到这题目觉得有些不简单,然后就还是没有思考就硬解,然后就用自己“强大”的脑袋瓜,写出了一套代码,透露这BFS的思想,但就是不知道自己用了BFS,当然在这种条件下,代码也是不可能跑出来的。
然后在discuss里面寻求帮助,找到了BFS三个大字,略略的看了眼代码,觉得自己会了,就来写了。。然后暂存的数据结构居然用了栈,硬生生的被我改成了DFS,,,,埃,活像个傻子。。最后参照优秀代码,又重新写了下,正确提交。

class Solution {
public:

    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        if(find(wordList.begin(),wordList.end(),endWord)==wordList.end()){ return 0;}
        int len = wordList.size();
        unordered_map <string,int> visited;
        unordered_map <string,bool> unvisited;
        for(int i=0;i<len;i++){
            unvisited[wordList[i]] = true;
        }
        visited[beginWord] = 1;
        queue<string> s;
        s.push(beginWord);
        while(!s.empty()){
            string tmp = s.front();
            s.pop();
            for(int i=0;i<len;i++){
                if(isOnlyOneDiff(tmp,wordList[i])&&unvisited[wordList[i]]){
                    s.push(wordList[i]);
                    //cout<<tmp<<"   "<<wordList[i]<<endl;
                    visited[wordList[i]] = visited[tmp] + 1;
                    if(wordList[i] == endWord){
                           return visited[wordList[i]];
                    }
                    unvisited[wordList[i]] = false;
                }
            }
        }

        return 0;
    }
private:
    bool isOnlyOneDiff(string a,string b){
        int times = 0;
        for(int i=0;i<a.size();i++){
            if(times > 1) return false;
            if(a[i]!=b[i]) times++;
        }
        if(times == 1) return true;
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40280096/article/details/81736891
今日推荐