126. 单词接龙 II

要求:跟127题区别是要找所有最短序列
思路:bfs找最短距离,dfs找所有路径

class Solution {
public:
    unordered_set<string> S; //对单词列表进行去重
    unordered_map<string,int> dist; //记录单词的最短路径
    queue<string> q;  //bfs用的队列
    vector<vector<string> > ans; //存放ans
    vector<string> path; //存放单条路径
    unordered_map<string, unordered_set<string> > from; //建立字符串之间的有向图
    string beginWord;  //存放beginwords用于dfs使用,减少参数传递

    vector<vector<string>> findLadders(string _beginWord, string endWord, vector<string>& wordList) {
        for(const auto& x : wordList)
            S.insert(x);
        beginWord = _beginWord;
        dist[beginWord] = 0;
        q.push(beginWord);

        while(!q.empty())
        {
            auto t = q.front(); q.pop();
            string r = t;
            for(int i = 0; i < t.size(); ++i)
            {
                t = r;
                for(char c = 'a'; c <= 'z'; ++c)
                {
                    t[i] = c;
                    //如果t存在于S中且是(第一次访问到t或者t的距离等于rd的距离+1),则建立对应的有向图
                    if(S.count(t) && (dist.count(t) == 0 || dist[t] == dist[r] + 1) )
                        from[t].insert(r);

                    bfs第一次遍历到的点一定是最短路径
                     //如果集合中存在t且是第一次遍历到该点
                    if(S.count(t) && dist.count(t) == 0)
                    {
                        dist[t] = dist[r] + 1;
                        if(t == endWord)
                            break;
                        q.push(t);
                    }
                }
            }
        }
        if(dist.count(endWord) == 0)    return ans;
        path.emplace_back(endWord);
        dfs(endWord);
        return ans;
    }

    void dfs(string t)
    {
        if(t == beginWord)
        {
            ans.push_back({path.rbegin(), path.rend()});
            return;
        }

        for(const auto& x : from[t]) //遍历t的源点
        {
            path.emplace_back(x);
            dfs(x);
            path.pop_back();
        }

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用Python完成题目的代码示例: ```python from collections import defaultdict, deque def findLadders(beginWord, endWord, wordList): # 构建单词到ID的映射关系 wordId = defaultdict(int) idWord = [] for word in wordList: if word not in wordId: wordId[word] = len(idWord) idWord.append(word) if endWord not in wordId: return [] # 构建图 graph = defaultdict(list) for word in wordList: for i in range(len(word)): mask = word[:i] + '*' + word[i+1:] graph[word].append(wordId[mask]) graph[wordId[mask]].append(wordId[word]) # 使用BFS找到最短路径 res = [] visited = defaultdict(bool) queue = deque([(wordId[beginWord], [[beginWord]])]) minLevel = float('inf') while queue: curWord, path = queue.popleft() if len(path) > minLevel: break if curWord == wordId[endWord]: res.append(path) minLevel = len(path) for neighbor in graph[curWord]: if not visited[neighbor]: visited[neighbor] = True queue.append((neighbor, path + [idWord[neighbor]])) return res # 测试样例 beginWord = "hit" endWord = "cog" wordList = ["hot", "dot", "dog", "lot", "log", "cog"] result = findLadders(beginWord, endWord, wordList) print(result) ``` 这段代码使用了广度优先搜索(BFS)来寻找最短路径。首先构建单词到ID的映射关系,然后构建图,图中的每个节点是一个单词,如果两个单词只有一个字母不同,则它们之间有一条边。接下来,使用BFS找到最短路径,并将结果存储在变量`res`中。最后,打印结果。 希望能对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值