LintCode-120: Word Ladder (经典BFS题)

  1. Word Ladder

Given two words (start and end), and a dictionary, find the shortest transformation sequence from start to end, output the length of the sequence.
Transformation rule such that:

Only one letter can be changed at a time
Each intermediate word must exist in the dictionary. (Start and end words do not need to appear in the dictionary )
Example
Example 1:

Input:start = “a”,end = “c”,dict =[“a”,“b”,“c”]
Output:2
Explanation:
“a”->“c”
Example 2:

Input:start =“hit”,end = “cog”,dict =[“hot”,“dot”,“dog”,“lot”,“log”]
Output:5
Explanation:
“hit”->“hot”->“dot”->“dog”->“cog”
Notice
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.

解法1:
BFS分层遍历,每次改动一个字符。
注意:
1)每次生成的string和dict里面的单词匹配的时候把string放入queue,同时dict里面对应的单词要删掉,不然会陷入死循环。
2) for循环里面每次操作完后要把curWord[j]=curChar改回去。
代码如下:

class Solution {
public:
    /*
     * @param start: a string
     * @param end: a string
     * @param dict: a set of string
     * @return: An integer
     */
    int ladderLength(string &start, string &end, unordered_set<string> &dict) {
        if (start==end) return 1;
        
        int strSize=start.size();
        if (strSize==0 || strSize!=end.size())
            return 0;
        
        queue<string> q;
        q.push(start);
        dict.erase(start);
        int length=1;
        
        while(!q.empty()) {
            int qSize=q.size();
            for (int i=0; i<qSize; ++i) {  //分层遍历,必须用到此for循环!
                string curWord=q.front();  
                q.pop();
                for (int j=0; j<strSize; ++j) {
                    char curChar=curWord[j]; //for position i, test 25 different letters.
                    for (char c='a'; c<'z'; ++c) {
                        if (c==curChar) continue;
                        curWord[j]=c;
                        if (curWord==end) {
                            return length+1;
                        }
                        if (dict.find(curWord)!=dict.end()) {
                            q.push(curWord);
                            dict.erase(curWord);
                        }
                    }
                    curWord[j]=curChar;   //position j done, will test position j+1 later      
                }
            }
            length++;
        }
    
        return 0;    
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值