D-Word_牛客小白月赛54 (nowcoder.com)
思路:
BFS求最短路的板子题
总结:
1.一般让你求某样东西变成另一样东西的最小步数就是去求最短路
2.这道题告诉我们求最短路不一定要建边,当数据范围较小时直接遍历也没有关系
3.输出方案一般按储存到链表然后后面写个循环输出即可
Code:
/*
抽象成BFS求最短路
并输出方案
*/
#include <bits/stdc++.h>
using namespace std;
const int mxn=2e3+10;
string s[mxn],st,ed;
queue<string> q;
vector<string> ans;
unordered_map<string,string> lst;
unordered_map<string,int> mp;
int n,m;
int main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>s[i],mp[s[i]]=-1;
cin>>st>>ed;
if(st==ed){cout<<0<<endl<<st<<endl<<ed;exit(0);}
s[++n]=ed;mp[ed]=-1;
q.push(st);
mp[st]=0;
while(!q.empty()){
string x=q.front();q.pop();
for(int i=1;i<=n;i++){
int res=0;
for(int j=0;j<m;j++){
if(x[j]!=s[i][j]) res++;
}
if(res==1){
if(mp[s[i]]==-1||mp[s[i]]>mp[x]+1){
mp[s[i]]=mp[x]+1;
lst[s[i]]=x;
q.push(s[i]);
}
}
}
}
if(mp[ed]==-1) cout<<-1;
else{
cout<<mp[ed]-1<<endl;
string now=ed;
ans.push_back(now);
while(lst[now]!="") ans.push_back(lst[now]),now=lst[now];
for(int i=ans.size()-1;i>=0;i--) cout<<ans[i]<<endl;
}
}