006:单词序列

006:单词序列

题目链接:http://cxsjsxmooc.openjudge.cn/2017t2summerfinal/006/

总时间限制:
1000ms
内存限制:
1024kB
描述

给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:

1、每次只能改变一个字母

2、转换过程中出现的单词(除开始单词和结束单词)必须存在于词典中

例如:

开始单词为:hit

结束单词为:cog

词典为:[hot,dot,dog,lot,log,mot]

那么一种可能的最短变换是: hit -> hot -> dot -> dog -> cog,

所以返回的结果是序列的长度5;

注意:

1、如果不能找到这种变换,则输出0;

2、词典中所有单词长度一样;

3、所有的单词都由小写字母构成;

4、开始单词和结束单词可以不在词典中。

输入
共两行,第一行为开始单词和结束单词(两个单词不同),以空格分开。第二行为若干的单词(各不相同),以空格分隔开来,表示词典。单词长度不超过5,单词个数不超过30。
输出
输出转换序列的长度。
样例输入
hit cog
hot dot dog lot log
样例输出
5
思路:广度优先搜索 需要构造一个词典(注意词典 内 单词的输入)

#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std ;
#define maxn 10
int total ; // 字典 中单词 数量  

char str11[maxn] , str22[maxn] ; 
char zidian[40][maxn] ; 
int visit[40] ; 
int len ; 
bool check(char str1[] , char str2[]  ){//相差一个字母返回真 
    int flag = 0 ; 
    for(int i=0 ; i<len ; i++){
        if(str1[i] != str2[i]){
            flag ++ ; 
        }
    }
    if(flag == 1)
        return true ;
    return false ; 
}

typedef struct node {
    char st[10] ;
    int step ; 
}Lnode ;
queue<Lnode>Q ; 

void DFS(char *str , int step){
    Lnode trun ; 
    strcpy(trun.st , str) ; 
    trun.step = step ; 
    Q.push(trun) ; 
    
    while(!Q.empty()){
        Lnode p = Q.front() ; 
        Q.pop() ; 
        if(check(p.st , str22)){//  模式串 到 目标串 差一个字母 (输出 +2 加上 开始单词 和 终止单词) 
            printf("%d
" , p.step+2) ; 
            return;
        }
        for(int i=0 ; i<total ; i++){
            if(check(p.st , zidian[i])&&!visit[i]){
                visit[i] = 1 ; 
                Lnode q ; 
                strcpy(q.st , zidian[i]) ; 
                q.step = p.step + 1 ; 
                Q.push(q) ; 
            }
        }
    }
    printf("0
") ;//  不能达到  (如果不能找到这种变换,则输出0) 
    return;
} 

int main(){
    while(~scanf("%s %s" , str11 , str22)){
        total = 0 ; 
        len = strlen(str11) ; 
        char ch ; 
        while(~scanf(" %s" , zidian[total++] )) {
            ch = getchar() ; 
            if(ch==' ') // 不知为什么 if(ch == '
') break ; 有问题... 
                continue ; 
            else 
                break ; 
        } 
    
        memset(visit , 0 , sizeof(visit)) ; 
        DFS(str11 , 0 ) ; 
    } 
    return 0 ; 
}  
原文地址:https://www.cnblogs.com/yi-ye-zhi-qiu/p/7586878.html