Leetcode-127.Word Ladder

Problem description :
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 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.


Analysis :
It’s a BFS problem. The idea is simpy to begin from start, then visit its neighbors, then the non-visited neighbors of its neighbors… Well, this is just the typical BFS structure.
First you might think try to find the word which dist is 1, then find the dist is 2….n ; However this method is slow when wordDict contains many word. It will get TLE.
There is a fast way that each time changing word every position from ‘a’ to ‘z’, as neighbour, then pushed into the queue. Then use BFS search the target. Also, to avoid visiting a word for more than once, we erase it from dict once it is visited.

This code will get TLE:

int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        queue<string> que;
        int length = 0;
        int tail = 0;
        que.push(beginWord);
        if(beginWord == endWord) return length;
        unordered_set <string> unvisited ;
        string tmp = "";
        int size = 1;
        while(!que.empty()) {
            for (int i = 0; i < size; i++)
            {
            tmp = que.front();
            que.pop();
            if (dist(tmp, endWord) == 1) return length  + 2; 
            auto itr = wordList.begin();
            while(itr != wordList.end()){
                string s = *itr;
                if(dist(tmp, s) == 1){
                    que.push(s);
                    itr = wordList.erase(itr);
                }
                else ++itr;

            }
            // for (auto& s : wordList){
            //  if (dist(tmp, s) == 1)
            //  {
            //      que.push(s);
            //      wordList.erase(s);
            //  }
            // }    
        }
            size = que.size();
            length++;
        }
        return 0;
    }
  int dist (string beginWord, string endWord)
    {
        int dist = 0;
        for (int i = 0; i < beginWord.size(); ++i)
        {
            if (beginWord[i] != endWord[i])
                dist++;
        }
        return dist;
    }

Here is the right code:

class Solution {
public:
   int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict)
 {
    wordDict.insert(beginWord);//insert to make code elegant;succinct
    wordDict.insert(endWord);
    queue<string> que;//check visited or not
    int step = 2;
    nextWord(beginWord, wordDict, que);// push the "neighbors" in que;
    while(!que.empty())
    {
        int last = que.size();
        for (int i = 0; i < last; ++i)//level traverse 
        {
            string word = que.front();
            que.pop();
            if (word == endWord) return step;
            nextWord(word, wordDict, que);
        }
        step++;
    }
    return 0;//no transimition sequence;
    }

 void nextWord(string word, unordered_set<string> & wordDict, queue<string> & que)// modified one char  check if it's in the worddict or not,
 {
    wordDict.erase(word);//erase the word which visited. avoid repeat
    for (int p = 0; p < word.size(); p++)
    for (int j = 0; j < 26; ++j)
    {
        string tmp = word;
        tmp[p] = 'a' + j;
        if (wordDict.count(tmp) > 0)//find the word in the wordDict
        {
            que.push(tmp);
            wordDict.erase(tmp); //delete,avoid revisited 
        }
    }
 }

};

This link provides a nice two-end search solution, which is much faster.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值