0%

[Leetcode]126. Word Ladder II(C++)

题目描述

题目链接:126. Word Ladder II

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

  • Every adjacent pair of words differs by a single letter.
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • sk == endWord
    Given two words, beginWord and endWord, and a dictionary wordList, return shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

例子

例子 1

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Explanation: There are 2 shortest transformation sequences:“hit” -> “hot” -> “dot” -> “dog” -> “cog”`"hit" -> "hot" -> "lot" -> "log" -> "cog"

例子 2

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord “cog” is not in wordList, therefore there is no valid transformation sequence.

Constraints

  • 1 <= beginWord.length <= 7
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the words in wordList are unique.

解题思路

[Leetcode]127. Word Ladder(C++) 思路类型,也是先构造图然后使用广度优先搜索来寻找最短路径,这道题要求返回所有最短的路径,因此在搜索过程我们还需要用一个哈希表来存储每个节点的母节点。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

class Solution {
public:
std::vector<std::vector<std::string>> findLadders(
std::string beginWord, std::string endWord,
std::vector<std::string>& wordList) {
std::vector<std::vector<std::string>> result;
// construct graph
std::queue<int> candidates;
for (int i = 0; i < wordList.size(); ++i) {
if (wordList[i] == endWord) {
candidates.push(i);
}
graph_[i] = {};
for (int j = 0; j < i; ++j) {
if (countDiff(wordList[i], wordList[j]) == 1) {
graph_[i].push_back(j);
graph_[j].push_back(i);
}
}
}

if (candidates.empty()) {
return result;
}

std::unordered_set<int> end_nodes;
std::unordered_map<int, int> used{{candidates.front(), 0}};
bool find_target = false;
int step = 1;
std::unordered_map<int, int> used_step;
while (!candidates.empty() && !find_target) {
std::queue<int> next;
while (!candidates.empty()) {
int curr_idx = candidates.front(); // parent & current idx
candidates.pop();

// cout << wordList[curr_idx] << endl;
if (countDiff(wordList[curr_idx], beginWord) == 1) {
find_target = true;
end_nodes.insert(curr_idx);
}

for (auto neighbor : graph_[curr_idx]) {
if (used.find(neighbor) == used.end() ||
used[neighbor] == step) {
// cout << "nei: " << neighbor << ", idx: " << curr_idx
// << std::endl;
next.push(neighbor);
parent_idx_[neighbor].push_back(curr_idx);
used[neighbor] = step;
}
}
}
candidates = next;
step++;
}

std::vector<std::string> curr{beginWord};

for (auto end : end_nodes) {
dfs(end, curr, result, wordList);
}

return result;
}

private:
std::unordered_map<int, std::vector<int>> parent_idx_;
std::unordered_map<int, std::vector<int>> graph_;

int countDiff(const std::string& first, const std::string& second) {
if (first.size() != second.size()) {
return -1;
}

int count = 0;
for (int i = 0; i < first.size(); ++i) {
count += (first[i] != second[i]);
}

return count;
}

void dfs(int idx, std::vector<std::string>& curr,
std::vector<std::vector<std::string>>& result,
const std::vector<std::string>& wordList) {
curr.push_back(wordList[idx]);
if (parent_idx_.find(idx) == parent_idx_.end()) {
result.push_back(curr);
} else {
for (auto parent : parent_idx_[idx]) {
dfs(parent, curr, result, wordList);
}
}
curr.pop_back();
}
};
  • 时间复杂度: O(|V| + |E|)
  • 空间复杂度: O(|E|)

GitHub 代码同步地址: 126.WordLadderIi.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions