leetcode207. Course Schedule

leetcode207. Course Schedule_第1张图片
image.png

其实就是判断图中是否存在环,拓扑排序的应用,构造有向图,找到入度为0的节点,BFS即可

 public boolean canFinish(int numCourses, int[][] prerequisites) {
      int[] inDegree = new int[numCourses];
        List[] graph = new ArrayList[numCourses];
        Queue queue = new LinkedList<>();
        for (int i = 0; i < graph.length; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int i = 0; i < prerequisites.length; i++) {
            graph[prerequisites[i][0]].add(prerequisites[i][1]);
            inDegree[prerequisites[i][1]]++;
        }
        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] == 0) queue.offer(i);
        }
        while (!queue.isEmpty()) {
            Integer top = queue.poll();
            for (Integer index : graph[top]) {
                --inDegree[index];
                if (inDegree[index] == 0) queue.offer(index);
            }
        }

        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] != 0) return false;
        }
        return true;
    }
}

你可能感兴趣的:(leetcode207. Course Schedule)