[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 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.

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

posted @ 2019-08-01 10:15  Review->Improve  阅读(3631)  评论(0编辑  收藏  举报