牛客小白月赛54 D-word

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;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值