【Leetcode】1136. Parallel Courses

题目地址:

https://leetcode.com/problems/parallel-courses/

给定一个课程的先修后修关系(即某个课程要修必须得其所有先修课程全修完才行),问至少要多少个学期能把所有课修完。每个学期修课数量不限制。如果不存在方案,则返回 − 1 -1 1

思路是拓扑排序。这里由于要计算拓扑排序的层数,所以只能用BFS来做。开个队列,先将所有入度为 0 0 0的点入队,然后进行分层遍历。每遍历一层的时候,就将其出边删去,一旦发现出边删去导致其邻接点入度为 0 0 0了,则将这个邻接点入队。BFS的时候累加层数和出队点的个数(出队点的个数就是已经排好序的点的个数)。最后,如果所有的点都出过队了,则说明存在拓扑排序,返回层数;否则返回 − 1 -1 1。代码如下:

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class Solution {
    public int minimumSemesters(int N, int[][] relations) {
    	// 邻接表建图,并且存一下每个点的入度
        int[] indegrees = new int[N];
        List<Integer>[] graph = buildGraph(relations, N, indegrees);
        
        // 先将入度为0的点入队
        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < N; i++) {
            if (indegrees[i] == 0) {
                queue.offer(i);
            }
        }
        
        int res = 0;
        while (!queue.isEmpty()) {
            res++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int cur = queue.poll();
                N--;
                if (graph[cur] != null) {
                    for (int next : graph[cur]) {
                        indegrees[next]--;
                        if (indegrees[next] == 0) {
                            queue.offer(next);
                        }
                    }
                }
            }
        }
        
        // 如果课没全修完,说明存在环,返回-1,否则返回学期数
        return N == 0 ? res : -1;
    }
    
    private List<Integer>[] buildGraph(int[][] relations, int N, int[] indegrees) {
        List<Integer>[] graph = (List<Integer>[]) new ArrayList[N];
        for (int[] relation : relations) {
            int from = relation[0] - 1, to = relation[1] - 1;
            if (graph[from] == null) {
                graph[from] = new ArrayList<>();
            }
            
            graph[from].add(to);
            indegrees[to]++;
        }
        
        return graph;
    }
}

时空复杂度 O ( V + E ) O(V+E) O(V+E)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值