我将如何减少该算法的冗余度?

问题描述 投票:1回答:1

我对C相当陌生,无法弄清楚如何使函数number_within_k_degrees()减少冗余。即使它们可能已经被访问过,它也会一次又一次地访问图的相同节点。我以为将所有值的初始设置都删除为false可以有所减少,但是我认为这样做没有多大作用。关于如何减少或消除多余工作的任何技巧将非常有帮助。谢谢

void find_reachable_recursive(struct person *current, int steps_remaining,
                              bool *reachable){
    // mark current root person as reachable
    reachable[person_get_index(current)] = true;
    // now deal with this person's acquaintances
    if (steps_remaining > 0){
        int num_known = person_get_num_known(current);
        for (int i = 0; i < num_known; i++){
            struct person *acquaintance = person_get_acquaintance(current, i);
            find_reachable_recursive(acquaintance, steps_remaining - 1, reachable);
        }
    }
}

// computes the number of people within k degrees of the start person
int number_within_k_degrees(struct person *start, int total_people, int k){
    bool *reachable;
    int count;

    // maintain a boolean flag for each person indicating if they are visited
    reachable = malloc(sizeof(bool) * total_people);
    for (int i = 0; i < total_people; i++){
        reachable[i] = false;
    }

    // now search for all people who are reachable with k steps
    find_reachable_recursive(start, k, reachable);

    // all visited people are marked reachable, so count them
    count = 0;
    for (int i = 0; i < total_people; i++){
        if (reachable[i] == true){
            count++;
        }
    }
    return count;
}
c redundancy
1个回答
1
投票

我认为应该将所有值的初始设置都删除为false,以使其有所减少

© www.soinside.com 2019 - 2024. All rights reserved.