LINTCODE——单词接龙

LINTCODE——单词接龙

思路:先设计一个无序图,然后宽度优先搜索遍历;

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) {
        // write your code here

        if(check(start,end))
            return 2;
        if(start == end)
            return 1;
        int n = dict.size();
        vector<string> dicts(dict.begin(),dict.end());

        //生成无向图,adj[i]里面存放的是能与dicts[i]直接转换的字符串下标
        vector<vector<int> > adj;
        for(int i = 0 ; i < n ; i++)
        {
            vector<int> temp;
            for(int j = 0 ; j < n ;j++)
            {
                if(i != j && check(dicts[i],dicts[j]))
                    temp.push_back(j);

            }
            adj.push_back(temp);
            temp.clear();
        }
        queue<int> Q;
        for(int i = 0 ; i < n ;i++)
            if(check(start,dicts[i]))
                Q.push(i);

        //宽度优先搜索,定义一个bool数组,记录访问过的元素
        vector<bool> record(n,false);
        int count = 1;
        while(!Q.empty())
        {
            int length = Q.size();
            while(length > 0)
            {
                int v = Q.front();
                Q.pop();
                for(auto x : adj[v])
                {
                    if(check(dicts[v],end))
                        return count+2;
                    if(!record[x])
                    {
                        record[x] = true;
                        Q.push(x);
                    }
                }
                length--;
            }
            count++;

        }
        return 0;

    }
    bool check(string a,string b)
    {
        int flag = 0;
        for(int i = 0 ; i < a.size() ; i++)
        {
            if(a[i] != b[i])
            {
                if(flag == 1)
                    return false;
                else
                    flag++;
            }

        }
        return (flag == 1) ? true : false;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值