单词接龙
2025-01-23 19:24:15
发布于:上海
#include<bits/stdc++.h>
using namespace std;
string a,b;
int n;
struct node{
string x;
int d;
};
unordered_map<string,int> mp;
unordered_set<string> st;
int main(){
cin>>a>>b;
cin>>n;
for(int i=0;i<n;i++){
string s;
cin>>s;
st.insert(s);
}
queue<node> q;
mp[a] = 0;
q.push({a,0});
while(q.size()){
node t = q.front();
q.pop();
string c = t.x;
int op = t.d;
for(int i=0;i<c.size();i++){
for(char j='a';j<='z';j++){
if(j==c[i])continue;
char back = c[i];
c[i]=j;
if(st.count(c)){
if(mp.find(c) == mp.end() || mp[c]>op+1){
mp[c] = op+1;
q.push({c,mp[c]});
}
}
c[i] = back;
}
}
}
if(mp.find(b) == mp.end())cout<<0;
else cout<<mp[b]+1;
return 0;
}
这里空空如也
有帮助,赞一个