leetcode-127. 单词接龙-C语言

/*
 * 算法思想:
 * 广度优先搜索,
 * 1. 需要一个队列辅助,这里使用数组代替,head与rear表示队列首尾;
 * 2. check()函数用于检测两个单词是否满足可转换的条件,即仅有一个字母不同;
 * 3. vst[]用于记录该index单词是否已经访问过。
 *
 */

bool check(char *s1, char *s2, int len){
    int i, flag = 0;

    for(i=0; i<len; i++){
        if(s1[i] != s2[i]){
            if(!flag) {
                flag = 1;
            }else{
                return false;
            }
        }
    }

    return flag;
}

typedef struct wd{
    int index;
    int d;
} Node;

#define LEN 0xfffff
int ladderLength(char * first, char * last, 
                 char ** wds, int wnum){
    Node que[LEN], *node;
    int head = 0, rear=0, i, j, len = strlen(wds[0]), last_index=INT_MAX;
    bool vst[wnum];
    
    memset(vst, 0, sizeof(vst));
    
    for(i=0; i<wnum; i++) {
        if(!strcmp(last, wds[i])){
            last_index = i;
            break;
        }
    }
    
    if(last_index==INT_MAX) {
        return 0;
    }
    
    que[head].index = last_index;
    que[head++].d = 1;
    vst[last_index] = 1;
    
    while(head > rear){
        node = &que[rear++];
        
        if(check(wds[node->index], first, len)){
            return node->d + 1;
        }
        
        for(i=0; i<wnum; i++) {
            if(!vst[i] && check(wds[node->index], wds[i], len)){
                que[head].index = i;
                que[head++].d = node->d + 1;
                vst[i] = 1;
            }
        }        
        
    }
    
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值