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

88 阅读2分钟

描述

在一个牧场中,有 numCows 头牛,编号为 0 到 numCows - 1。牧场主为了方便管理,记录了牛群之间的喂养顺序关系。喂养顺序关系用一个数组 feedOrders 给出,其中 feedOrders[i] = [ai, bi],表示如果要喂养牛 ai,则必须先喂养牛 bi。 例如,喂养顺序对 [0, 1] 表示:想要喂养牛 0,你需要先喂养牛 1。
返回你为了喂养完所有牛所安排的喂养顺序,不会出现多个答案的情况。如果不可能喂养完所有牛,返回一个空数组。

示例1

输入:2,[[1,0]]
返回值:[0,1]
说明:总共有 2 头牛。要喂养牛 1,你需要先喂养牛 0。因此,正确的喂养顺序为 [0,1] 。

知识点

队列,拓扑排序

Java题解

public int[] findFeedOrderII (int numCows, int[][] feedOrders) {
        // write code here
        ArrayList<Integer>[] graph = new ArrayList[numCows];
        int[] indegrees = new int[numCows];
        // 初始化图和入度数组
        for (int i = 0; i < numCows; i++) {
            graph[i] = new ArrayList<>();
        }
        // 构建有向图和入度数组
        for (int[] order : feedOrders) {
            int cowA = order[0];
            int cowB = order[1];
            graph[cowB].add(cowA);
            indegrees[cowA]++;
        }
        // 使用队列进行拓扑排序
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCows; i++) {
            if (indegrees[i] == 0) {
                queue.offer(i);
            }
        }
        List<Integer> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            int cow = queue.poll();
            result.add(cow);
            // 减少依赖于当前牛的入度
            for (int nextCow : graph[cow]) {
                if (--indegrees[nextCow] == 0) {
                    queue.offer(nextCow);
                }
            }
        }
        // 如果没有遍历到所有的牛,则说明无法喂养完所有牛
        if (result.size() != numCows) {
            return new int[0];
        }
        // 将结果转换为数组并返回
        int[] feedOrder = new int[numCows];
        for (int i = 0; i < numCows; i++) {
            feedOrder[i] = result.get(i);
        }

        return feedOrder;
    }

解题思路

拓扑排序算法的基本思想是不断移除入度为0的节点,直到所有节点都被移除或者没有入度为0的节点。在本题中,入度为0的节点表示可以直接喂养的牛。用数组graph来表示有向图中每个节点的后继节点,并使用数组indegress来记录每个节点的入度。 然后,使用队列进行拓扑排序。将所有入度为0的节点入队,并依次取出队列中的节点,将其加入结果数组result,并将与其相邻的节点的入度减一。如果减一后的入度为0,则将该节点入队。 当队列为空时,如果result数组的大小不等于牛的数量nuwCows,则说明无法喂养完所有牛,返回一个空数组。 最后,将result数组转换为整型数组feedOrder并返回。