题解 | #牛群的喂养顺序#

牛群的喂养顺序

https://www.nowcoder.com/practice/ce8860b6a8c74dfd8ccd15998970e447

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param numCows int整型
 * @param feedOrders int整型二维数组
 * @param feedOrdersRowLen int feedOrders数组行数
 * @param feedOrdersColLen int* feedOrders数组列数
 * @return bool布尔型
 */
#include <stdbool.h>
#include <stdio.h>
struct Parent {
    int parent;
};
bool findParent(struct Parent* nums, int x) {
    int origin = x;
    while (nums[x].parent != x) {
        x = nums[x].parent;
        if (x == -1) return false;
        if (x == origin) return true;
    }
    return false;
}
#include <string.h>
bool canFeedAllCows(int numCows, int** feedOrders, int feedOrdersRowLen,
                    int* feedOrdersColLen ) {
    int visited[numCows];
    int count = 0;
    memset(visited, 0, sizeof(int)*numCows);
    struct Parent nums[numCows];
    memset(nums, -1, sizeof(struct Parent)*numCows);
    for (int i = 0; i < feedOrdersRowLen; i++) {
        nums[feedOrders[i][0]].parent = feedOrders[i][1];
    }
    for (int i = 0; i < feedOrdersRowLen; i++) {
        int num = nums[feedOrders[i][0]].parent;
        if (findParent(nums, num)) return false;
        else {
            if (visited[feedOrders[i][0]] == 0) {
                count++;
                visited[feedOrders[i][0]] = 1;
            }
            if (visited[feedOrders[i][1]] == 0) {
                count++;
                visited[feedOrders[i][1]] = 1;
            }
        }
    }
    if (count == numCows) return true;
    return false;
}

全部评论

相关推荐

02-08 15:53
门头沟学院 Java
CoderEcho:让公司知道便宜没好货
点赞 评论 收藏
分享
02-26 18:25
已编辑
南京大学 算法工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务