【leetcode】 word ladder

问题:

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord to endWord, such that:

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

For example,

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

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.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

分析:

1、BFS,解题思路可见http://www.cnblogs.com/ShaneZhang/p/3748494.html;

2、leetcode在2017.1.20更新了word ladder这道题,将wordlist从unordered_set改为vector类型

(作为一枚编程菜鸟,我在程序中又将vector改回unordered_set类型了。。。)

3、欢迎指正!

代码:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& DictList) {
       unordered_set<string> DictSet;
       for(string w:DictList){
           DictSet.insert(w);
       }
       queue<string> toVisit;
       addNextWord(beginWord,DictSet,toVisit);
       int dist=2;
       //BFS遍历
       while(!toVisit.empty()){
           int n=toVisit.size();
           //看当前单词的邻居中
           for(int j=0;j<n;j++){
               string word=toVisit.front();
               toVisit.pop();
               //若有endWord,则返回距离
               if(word==endWord) return dist;
               //将当前单词的邻居的邻居放入队列中
               addNextWord(word,DictSet,toVisit);
           }
           //当前词典的邻居都无endWord,则这一层遍历结束;故BFS深度加一
           dist++;
       }
       //BFS遍历结束,还未找到endWord,则无法构成transform
       return 0;
    }
private:
    void addNextWord(string& word,unordered_set<string>& Dict,queue<string>& toVisit){
       //当前单词从词典dict中删去
        Dict.erase(word);
        for(int p=0;p<word.length();p++){
            char letter=word[p];
            for(int i=0;i<26;i++){
                word[p]='a'+i;
                if(Dict.find(word)!=Dict.end()){
                    //当前单词的邻居从词典中删去,并放入待访问的队列中
                    Dict.erase(word);
                    toVisit.push(word);
                }
            }
            //每次只改变一个字符
            word[p]=letter;
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值