word-ladder 问题

/*************************************************************************
  * File Name: Solution.cpp
  * Description: 
  * Author: Yuji CAO
  * Mail: caoyuji@sogou-inc.com
  * Created_Time: 2015-07-31 10时13分23秒
  * Last modified: 2015-07-31 10时13分23秒
 ************************************************************************/
#include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<unordered_map>
#include<unordered_set>
using namespace std;
class Solution{
public:
    int ladderPath(unordered_set<string>& dic,string &src,string &dst){
        dic.insert(dst);
        dic.insert(src);
        queue<string> q;
        q.push(src);
        _color.insert(src);
        while(!q.empty()){
            string tmp=q.front();
            q.pop();
            for(int i=0;i<(int)tmp.length();++i){
                for(char ele='a';ele<='z';++ele){
                    if(ele!=tmp[i]){
                        string adjTmp(tmp);
                        adjTmp[i]=ele;
                        if(dic.find(adjTmp)!=dic.end()){
                            if(_color.find(adjTmp)==_color.end()){//没有访问过的临节点
                                _parent[adjTmp]=tmp;
                                _color.insert(adjTmp);
                                q.push(adjTmp);
                            }
                        }
                    }
                }
            }
        }
        int pathLen=0;
        printPath(src,dst,pathLen);
        return pathLen;
    }

    void printPath(string& src,string& dst,int &pathLen){
        cout<<src.c_str();
        printPath(dst,pathLen);
    }
    void printPath(string& dst,int &pathLen){
        if(_parent.find(dst)==_parent.end()){
            //cout<<endl;
            return;
        }
        printPath(_parent[dst],pathLen);
        cout<<"->"<<dst.c_str();
        pathLen++;
    }
private:
    unordered_set<string> _color;
    unordered_map<string,string> _parent;
};

int main(){
    Solution s;
    string d[]={"hot","log","dot","dog","lot"};
    vector<string> dat(d,d+5);
    unordered_set<string> dic(dat.begin(),dat.end());
    string start("hit");
    string end("cog");
    int len=s.ladderPath(dic,start,end);
    cout<<"\npath-length:"<<len<<endl;
    return 0;
}

分析

在不构造图数据的情况下模拟图的广度优先便历,是本题的难点!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值