6.12考试 T1 单词序列

1

2()

hit

cog

[hot,dot,dog,lot,log,mot]

hit->hot->dot->dog->cog,

5

10

2

3

4

5,30

输入样例1:

hit cog
hot dot dog lot log

输出样例1:

5

该题其他输入输出数据:https://share.weiyun.com/5tpaeKV

思路:

广搜。

1、如果当前单词与结束单词差异度为0,直接输出当前深度,return 0;

2、’如果当前单词与正在搜索的单词差异度为1,那我们就把该单词加入队列中,深度为父节点的深度+1;

3、如果当前深度大于总单词数,则证明无法找到一条路径转换到结束单词。

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int n,num=1;
char s[38][6],be[6];
char w[200008][6];
int h=1,t=0;
int deep[200008];

int fc(char a[],char b[])
{
    int cnt=0;
    for(int i=0;i<n;++i)
    {
        if(a[i]!=b[i]) cnt++;
        else continue;
    }
    return cnt;
}

int main()
{
    freopen("word.in","r",stdin);
    freopen("word.out","w",stdout);
    scanf("%s",be);
    n=strlen(be);
    while(~scanf("%s",s[num])) num++;
    num--;
    t++;
    deep[t]=1;
    strcpy(w[t],be);
    while(h<=t)
    {
        if(deep[h]>num+2) break; 
        if(fc(w[h],s[1])==0)
        {
            printf("%d",deep[h]);
            return 0;
        }
        for(int i=1;i<=num;++i)
        {
            if(fc(w[h],s[i])==1)
            {
                t++;
                strcpy(w[t],s[i]);
                deep[t]=deep[h]+1;
            }
            else continue;
        }
        h++;
    }
    printf("%d",0);
    return 0;
} 
原文地址:https://www.cnblogs.com/-hhs/p/11009598.html