leetcode Word Ladder II

本文介绍了一种使用宽度优先搜索(BFS)和深度优先搜索(DFS)算法来寻找两个单词间最短转换路径的方法。通过建立单词之间的转换图,并逆向追踪路径,实现了寻找所有可能的最短转换序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector<string> one_result;
vector<vector<string> > result;
map<string, int> word_deep_map; //某个单词在第几层上。
int word_lenght;


/* 宽度搜索 建立graph(记录单词的层次) */
void bfs(string &start, string &end, set<string> &dict)
{
    queue<string> word_queue;// 把当前单词变换后的在字典中的单词 放在队列里
    word_queue.push(start);
    word_deep_map.insert(make_pair(start, 1));

    while(!word_queue.empty())
    {
        string now_word = word_queue.front();
        word_queue.pop();
        if(now_word == end)
            continue;


        string tmp_word;
        for(int i = 0; i < word_lenght; ++i)//对单词的每一个字符
        {
            tmp_word = now_word;
            for(int j = 'a'; j <= 'z'; ++j)
            {
                tmp_word[i] = j;//j 替换 单词的第i个字符
                /* (替换后的单词在字典中 ||  是最后一个单词(把最后一个单词也放进graph) ) && 之前没有被添加进graph */
                if((dict.count(tmp_word) > 0 || tmp_word == end) && word_deep_map.count(tmp_word) == 0)
                {
                    word_queue.push(tmp_word);
                    word_deep_map.insert(make_pair(tmp_word, word_deep_map[now_word] + 1));//上一个单词深度+1
                }
            }
        }//end for
    }//end while word_queue
}



/* 从尾部开始搜索 end是最初的start*/
void dfs(string current_word,string &end, set<string> &dict)
{
    if(current_word == end)
    {
        one_result.push_back(end);
        reverse(one_result.begin(),one_result.end());
        result.push_back(one_result);
        reverse(one_result.begin(),one_result.end());
        return;
    }

    one_result.push_back(current_word);
    string tmp_word;
    /* word_deep_map 只记录了该单词在第几层,没有对应关系,所以还需要检查单词  */
    for(int i = 0; i < word_lenght; ++i)
    {
        tmp_word = current_word;
        for(int j = 'a'; j <= 'z'; ++j)
        {
            tmp_word[i] = j;
            /* 新单词 在graph中存在 &&  是当前单词的前一层(即 深度减一) */
            if(word_deep_map.count(tmp_word) > 0 && word_deep_map[tmp_word] == word_deep_map[current_word] - 1)
            {
                dfs(tmp_word, end, dict);
                one_result.pop_back();
            }
        }
    }
}



vector<vector<string> > findLadders(string start, string end, set<string> &dict)//unordered_set
{
    if(start.empty() || end.empty() || start.size() != end.size())
        return result;
    if(start == end)
    {
        one_result.push_back(start);
        result.push_back(one_result);
        return result;
    }
    if(dict.empty())
        return result;

    word_lenght = start.size();
    bfs(start, end, dict);// 宽度搜索,算出每个单词在树的第几层上
    dfs(end, start, dict);// 从尾部开始搜索
    return result;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值