[LeetCode 1136] Parallel Courses

There are N courses, labelled from 1 to N.

We are given relations[i] = [X, Y], representing a prerequisite relationship between course Xand 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.

Example 2:

Input: N = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: 
No course can be studied because they depend on each other.

 

Note:

  1. 1 <= N <= 5000
  2. 1 <= relations.length <= 5000
  3. relations[i][0] != relations[i][1]
  4. There are no repeated relations in the input.

 

 Solution 1. Greedy Algorithm with BFS.

Since we can take as many courses as we want, taking all courses that do not have outstanding prerequisites each semester must be one valid answer that gives a minimum number of semesters needed. 

1.  Construct a directed graph and in degree of each node(course).

2. Add all courses that do not have any prerequisites(in degree == 0) to a queue.

3. BFS on all neighboring nodes(courses) of the starting courses and decrease their indegrees by 1.  If a neighboring course's indegree becomes 0, it means all its prerequisites are met, add it to queue as this course can be taken in the next semester. 

4. After all neighboring nodes of the courses that are taken in the current semester have been visited, increment semester count by 1. Repeat until the queue is empty.

5. When doing the BFS, keep a count of courses taken, compare this count with the total number of courses to determine if it is possible to study all courses.

 

Both the runtime and space are O(V+E). 

class Solution {
    public int minimumSemesters(int N, int[][] relations) {
        Map<Integer, Set<Integer>> graph = new HashMap<>();
        int[] inDegree = new int[N + 1];
        
        for(int i = 1; i <= N; i++) {
            graph.put(i, new HashSet<>());
        }
        for(int[] edge : relations) {
            if(graph.get(edge[0]).add(edge[1])) {
                inDegree[edge[1]]++;
            }
        }   
        
        Queue<Integer> q = new LinkedList<>();
        int semester = 0, course = 0;
        for(int i = 1; i <= N; i++) {
            if(inDegree[i] == 0) {
                q.add(i);           
            }
        }
        while(q.size() > 0) {
            int sz = q.size();
            course += sz;
            for(int i = 0; i < sz; i++) {
                int curr = q.poll();
                for(int neighbor : graph.get(curr)) {
                    inDegree[neighbor]--;
                    if(inDegree[neighbor] == 0) {
                        q.add(neighbor);
                    }
                }               
            }
            semester++;
        }
        return course == N ? semester : -1;
    }
}

 

Solution 2. DFS with Dynamic Programming

Because we have to first take all prerequisites of a course beforing taking it, we know the following two property of this problem.

1. If there is a cycle, there is no way of studying all courses.

2. If there is no cycle, the minimum number of semesters needed to study all courses is determined by the longest acyclic path, i.e, we are looking for the longest acyclic path with each edge's weight being 1. This is exactly the same problem with Max path value in directed graph. The only difference is the dynamic programming state.

 

Both runtime and space are O(V+E).

class Solution {
    private final int UNVISITED = 0;
    private final int VISITING = 1;
    private final int VISITED = 2;
    private int[] longestPath;
    private int[] states;
    public int minimumSemesters(int N, int[][] relations) {
        Map<Integer, Set<Integer>> graph = constructGraph(N, relations);
        longestPath = new int[N + 1];
        states = new int[N + 1];
        
        for(int course = 1; course <= N; course++) {
            if(states[course] == UNVISITED) {
                if(dfs(graph, course)) {
                    return -1;
                }
            }
        }
        int ans = 0;
        for(int course = 1; course <= N; course++) {
            ans = Math.max(ans, longestPath[course]);
        }
        return ans;
    }
    
    private Map<Integer, Set<Integer>> constructGraph(int N, int[][] relations) {
        Map<Integer, Set<Integer>> graph = new HashMap<>();
        for(int i = 1; i <= N; i++) {
            graph.put(i, new HashSet<>());
        }
        for(int i = 0 ; i < relations.length; i++) {
            graph.get(relations[i][0]).add(relations[i][1]);
        }
        return graph;
    }
    
    private boolean dfs(Map<Integer, Set<Integer>> graph, int course) {
        if(states[course] == VISITED) {
            return false;
        }
        else if(states[course] == VISITING) {
            return true;
        }
        states[course] = VISITING;
        for(int neighbor : graph.get(course)) {
            if(dfs(graph, neighbor)) {
                return true;
            }
        }
        for(int neighbor : graph.get(course)) {
            longestPath[course] = Math.max(longestPath[course], longestPath[neighbor]);
        }
        longestPath[course]++;
        states[course] = VISITED;
        return false;
    }
}

 

 

Related Problems

Topological Sorting

Max path value in directed graph

转载于:https://www.cnblogs.com/lz87/p/11280484.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值