一个广搜完事,写了半天
const int MAX_N = 40000;
struct Edge {
int to, next;
};
struct Node {
int index, step;
vector<string> v;
};
int head[MAX_N], tot;
Edge edge[MAX_N * 8];
map<string, int> mp;
map<int, string> mpl;
vector<vector<string>> ansvec;
class Solution {
public:
void add_edge(int a, int b) {
edge[tot].to = b;
edge[tot].next = head[a];
head[a] = tot++;
edge[tot].to = a;
edge[tot].next = head[b];
head[b] = tot++;
}
bool judge(string a, string b) {
if (a.size() == b.size()) {
int cnt = 0;
for (int i = 0; i < a.size(); i++) {
if (a[i] != b[i]) {
cnt++;
}
}
return cnt == 1;
}
return false;
}
vector<vector<string>> bfs(int st, int ed) {
queue<Node> q;
Node temp;
temp.index = st;
temp.step = 0;
temp.v.push_back(mpl[st]);
q.push(temp);
bool mark[MAX_N];
memset(mark, false, sizeof(mark));
mark[st] = true;
vector<vector<string>> ans;
int minstep = 1e10;
while (!q.empty()) {
int sz = q.size();
queue<int> tempp;
while (sz--) {
Node n = q.front();
q.pop();
if (n.index == ed) {
ans.push_back(n.v);
minstep = n.step;
continue;
//return n.step;
}
for (int i = head[n.index]; i != -1; i = edge[i].next) {
if (edge[i].to != ed && mark[edge[i].to]) {
continue;
}
Node temp;
temp.index = edge[i].to;
temp.step = n.step + 1;
if (temp.step > minstep) {
continue;
}
temp.v = n.v;
temp.v.push_back(mpl[edge[i].to]);
q.push(temp);
//mark[edge[i].to] = true;
tempp.push(edge[i].to);
}
}
while (!tempp.empty()) {
mark[tempp.front()] = true;
tempp.pop();
}
}
return ans;
}
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
tot = 0;
ansvec.clear();
mp.clear();
mpl.clear();
int index = 0;
memset(head, -1, sizeof(head));
for (auto i : wordList) {
if (mp[i] != 0) {
continue;
}
else {
mp[i] = ++index;
mpl[index] = i;
}
}
if (mp[beginWord] == 0) {
mp[beginWord] = ++index;
mpl[index] = beginWord;
}
if (mp[endWord] == 0) {
mp[endWord] = ++index;
mpl[index] = endWord;
}
for (int i = 0; i < wordList.size(); i++) {
for (int j = i + 1; j < wordList.size(); j++) {
if (wordList[i] == beginWord) continue;
if (wordList[j] == beginWord) continue;
if (judge(wordList[i], wordList[j])) {
add_edge(mp[wordList[i]],mp[wordList[j]]);
}
}
if (wordList[i] != beginWord && judge(wordList[i], beginWord)) {
add_edge(mp[wordList[i]], mp[beginWord]);
}
}
return bfs(mp[beginWord], mp[endWord]);
}
};