leetcode Word Ladder

Word Ladder

  Total Accepted: 17709  Total Submissions: 96915 My Submissions

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

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["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.

Have you been asked this question in an interview? 

Discuss

      初次接触这样题目的人,会看不懂题目的意图。其实这个跳跃,可以看成一幅图,只有一个字母不同的两个单词之间有连线,其他没有。这样,最小的跳跃长度,就是图的最短路径。

      由于这幅图之间每个节点的距离相等,所以使用广度优先搜索就可以找到最短路径。

1. 由于是图的搜索,所以需要标记节点是否访问过的方法,我就用set来实现,如果set中包含某个单词,那么这个单词就没有被访问过。

    否则,把这个单词加入到vist集合当中。

2. 对于单词之间的距离,由于字母总共有26个,所以可以用暴力的方法来求距离相聚为一的两个单词。

3.在搜索时,每向外圈多扩展一圈,就把步数加一。最后遇到目的单词,搜索结束。


class Solution
{
    public:
    int ladderLength(string start,string end,unordered_set<string> &dict)
    {
        set<string> visit;
        int count = 1,len = 0,i=0,j=0,k=0;
        int len2 = start.size();
        queue<string> que;
        if(start.compare(end)==0)
        {
            return 1;
        }
        que.push(start);
        visit.insert(start);
        while(que.size()>0)
        {
            len = que.size();
            //cout<<que.size()<<endl;
            for(i=0;i<len;i++)
            {
                string tmp = que.front();
                que.pop();
                for(j=0;j<len2;j++)
                {
                    char tc = tmp[j];
                    for(k='a';k<'z';k++)
                    {
                        tmp[j] = k;
                        // remember the dictionary
                        if(dict.count(tmp)!=0)
                        {
                        if(visit.count(tmp)==0)
                        {
                            if(tmp.compare(end)==0)
                            {
                                //cout<<tmp<<endl;
                                return count+1;
                            }
                            visit.insert(tmp);
                            que.push(tmp);
                        }
                        }
                    }
                    tmp[j] = tc;
                }
            }
            count++;
        }
    
    return 0;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值