Word Ladder



以为是广度优先,结果有环的图的递归果然还是包括深度优先了!所以以下代码悲剧错了!!!

class Solution {
public:

    int min_depth;
    void dfs(string &start,string &end, unordered_set<string> &dict,int depth)
    {
        if(min_depth!=INT_MAX) return;
        
        if(start==end) min_depth=depth;
        
        
        vector<string> toDetect;
        for(int i=0;i<start.length();i++)
        {
            char c=start[i];
            for(char j='a';j<='z';j++)
            {
                if(start[i]==j) continue;
                start[i]=j;
                std::unordered_set<std::string>::const_iterator got = dict.find (start);
                if(got!=dict.end())
                {
                    toDetect.push_back(start);
                    dict.erase(got);
                }
                start[i]=c;
            }
        }
        
        for(int i=0;i<toDetect.size();i++)
        {
            dfs(toDetect[i],end,dict,depth+1);
        }
    }
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       min_depth=INT_MAX;
       
       dfs(start,end,dict,1);
       
       if(min_depth==INT_MAX) return 0;
       
       return min_depth;
       
    }
};



哎,还是完全模仿网上代码!没有原创性。

学习了swap函数的使用。

更加熟悉了dfs,bfs区别。


class Solution {
public:

    int ladderLength(string start, string end, unordered_set<string> &dict) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<string> toPop,toPush;
        toPop.push(start);
        
        int depth=0;
        
        while(!toPop.empty())
        {
            while(!toPop.empty())
            {
                string begin=toPop.top();
                toPop.pop();
                
                if(begin==end) return depth+1;
                
                for(int i=0;i<begin.length();i++)
                {
                    char c=begin[i];
                    for(char j='a';j<='z';j++)
                    {
                        if(begin[i]==j) continue;
                        begin[i]=j;
                        std::unordered_set<std::string>::const_iterator got = dict.find (begin);
                        if(got!=dict.end())
                        {
                            toPush.push(begin);
                            dict.erase(got);
                        }
                        begin[i]=c;
                    }
                }
            }
            swap(toPush,toPop);
            depth++;
        }
       
       
       return 0;
       
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值