背
这道题最大的影响在于bfs的时候不好找到next节点,就是说不好建图。需要借助一个中间变量来完成,例如hit变成hot,可以做一个哈希,unordered_map<string, vector<string>> next_map;
,其中key是h*t
,value是所有可以所有满足h*t
的string的vector。遍历一次wordList的vector,每个出现的string,都对其的所有位进行一次查找。例如hit,先出现*it
,在next_map中添加一条key=*it
,value push_back一下hit。
这样等正式找的时候,hit,先找*it
在next_map对应的vector,如果这个元素没有访问过,就push进bfs内,再找h*t
对应的vector,再找hi*
的。
#include <stdc++.h>
using namespace std;
int ladderLength(string beginWord, string endWord,
const vector<string>& wordList) {
queue<string> bfs;
int count = 0;
unordered_map<string, vector<string>> next_map;
unordered_set<string> visited;
int n = static_cast<int>(beginWord.length());
for (auto str : wordList) {
for (int i = 0; i < n; ++i) {
auto str_tmp = str;
str_tmp[i] = '*';
next_map[str_tmp].push_back(str);
}
}
if (beginWord == endWord) return 0;
bfs.push(beginWord);
visited.insert(beginWord);
while (!bfs.empty()) {
queue<string> bfs_tmp;
bfs.swap(bfs_tmp);
++count;
while (!bfs_tmp.empty()) {
auto str = bfs_tmp.front();
bfs_tmp.pop();
for (int i = 0; i < n; ++i) {
auto str_tmp = str;
str_tmp[i] = '*';
if (next_map.find(str_tmp) != next_map.end()) ///< hi*对应的vector
{
for (auto next_node : next_map[str_tmp]) {
if (visited.find(next_node) == visited.end()) {
if (next_node == endWord) return count + 1;
bfs.push(next_node);
visited.insert(next_node);
}
}
}
}
}
}
return 0;
}
int main() {
cout << ladderLength("hit", "cog", {"hot", "dot", "dog", "lot", "log"})
<< endl;
return 0;
}