Parallel Courses

There are N courses, labelled from 1 to N.

We are given relations[i] = [X, Y], representing a prerequisite relationship between course X and course Y: course X has to be studied before course Y.

In one semester you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.

Return the minimum number of semesters needed to study all courses.  If there is no way to study all the courses, return -1.

Example 1:

Input: N = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation: 
In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.

思路:就是topo排序和level order,注意indegree要用array来表示就可以了;x -> y, x的neighbor加入y;y 的indegree ++;

class Solution {
    public int minimumSemesters(int N, int[][] relations) {
        if(N < 0 || relations == null) {
            return -1;
        }
        HashMap<Integer, List<Integer>> graph = new HashMap<>();
        for(int i = 1; i <= N; i++) {
            graph.putIfAbsent(i, new ArrayList<Integer>());
        }
        // indegree 用array表示即可;
        int[] indegree = new int[N + 1];
        for(int i = 0; i < relations.length; i++) {
            int x = relations[i][0];
            int y = relations[i][1];
            graph.get(x).add(y);
            indegree[y]++;
        }
        
        Queue<Integer> queue = new LinkedList<Integer>();
        for(int i = 1; i <= N; i++) {
            if(indegree[i] == 0) {
                queue.offer(i);
            }
        }
        
        int step = 0;
        int count = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                count++;
                Integer node = queue.poll();
                for(Integer neighbor: graph.get(node)) {
                    indegree[neighbor]--;
                    if(indegree[neighbor] == 0) {
                        queue.offer(neighbor);
                    }
                }
            }
            step++;
        }
        return count == N ? step : -1;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值