力扣127——单词接龙
广度优先搜索 + 优化建图
1.无向图,无权重
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <climits>
using namespace std;
class Solution {
public:
unordered_map<string, int> wordId;
vector<vector<int>> edge;
int nodeNum = 0;
void addWord(string& word) {
if (!wordId.count(word)) {
wordId[word] = nodeNum++;
edge.emplace_back();
}
}
void addEdge(string& word) {//举例hot
addWord(word);//添加hot
int id1 = wordId[word];//获取id
for (char& it : word) {//字母字符遍历h、o、t
char tmp = it;
it = '*';//此时*ot
addWord(word);//依次添加*ot、h*t、ho*
int id2 = wordId[word];
edge[id1].push_back(id2);
edge[id2].push_back(id1);
it = tmp;//转换回hot
}
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
for (string& word : wordList) {
addEdge(word);//添加word-id的无序map映射
}
addEdge(beginWord);//添加begin
if (!wordId.count(endWord)) {//检查endWord是否存在
return 0;
}
vector<int> dis(nodeNum, INT_MAX);//初始化nodeNum数量的数组
int beginId = wordId[beginWord], endId = wordId[endWord];//通过map提取字符串对应的编号
dis[beginId] = 0;
queue<int> que;
que.push(beginId);
while (!que.empty()) {
int x = que.front();
que.pop();
if (x == endId) {
return dis[endId] / 2 + 1;
}
for (int& it : edge[x]) {//从begin开始依次遍历二维数组的关联字符串的编号
if (dis[it] == INT_MAX) {//将满足条件的所有字符串(相差一个字符)全部压入队列中 挨个往下遍历
dis[it] = dis[x] + 1;//更新入队条件
que.push(it);
}
}
}
return 0;
}
};
双向广度优先搜索
class Solution {
public:
unordered_map<string, int> wordId;
vector<vector<int>> edge;
int nodeNum = 0;
void addWord(string& word) {
if (!wordId.count(word)) {
wordId[word] = nodeNum++;
edge.emplace_back();
}
}
void addEdge(string& word) {
addWord(word);
int id1 = wordId[word];
for (char& it : word) {
char tmp = it;
it = '*';
addWord(word);
int id2 = wordId[word];
edge[id1].push_back(id2);
edge[id2].push_back(id1);
it = tmp;
}
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
for (string& word : wordList) {
addEdge(word);
}
addEdge(beginWord);
if (!wordId.count(endWord)) {
return 0;
}
vector<int> disBegin(nodeNum, INT_MAX);
int beginId = wordId[beginWord];
disBegin[beginId] = 0;
queue<int> queBegin;
queBegin.push(beginId);
vector<int> disEnd(nodeNum, INT_MAX);
int endId = wordId[endWord];
disEnd[endId] = 0;
queue<int> queEnd;
queEnd.push(endId);
while (!queBegin.empty() && !queEnd.empty()) {
int queBeginSize = queBegin.size();
for (int i = 0; i < queBeginSize; ++i) {
int nodeBegin = queBegin.front();
queBegin.pop();
if (disEnd[nodeBegin] != INT_MAX) {
return (disBegin[nodeBegin] + disEnd[nodeBegin]) / 2 + 1;
}
for (int& it : edge[nodeBegin]) {
if (disBegin[it] == INT_MAX) {
disBegin[it] = disBegin[nodeBegin] + 1;
queBegin.push(it);
}
}
}
int queEndSize = queEnd.size();
for (int i = 0; i < queEndSize; ++i) {
int nodeEnd = queEnd.front();
queEnd.pop();
if (disBegin[nodeEnd] != INT_MAX) {
return (disBegin[nodeEnd] + disEnd[nodeEnd]) / 2 + 1;
}
for (int& it : edge[nodeEnd]) {
if (disEnd[it] == INT_MAX) {
disEnd[it] = disEnd[nodeEnd] + 1;
queEnd.push(it);
}
}
}
}
return 0;
}
};