Skip to content

Parallel Courses⚓︎

Link

Description⚓︎

You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCourse_i, nextCourse_i], representing a prerequisite relationship between course prevCoursei and course nextCourse_i: course prevCourse_i has to be taken before course nextCourse_i.

In one semester, you can take any number of courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking.

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

Example 1:

Ex1

  • Input: n = 3, relations = [[1,3],[2,3]]
  • Output: 2
  • Explanation:
1
2
3
The figure above represents the given graph.
In the first semester, you can take courses 1 and 2.
In the second semester, you can take course 3.

Example 2:

Ex2

  • Input: n = 3, relations = [[1,2],[2,3],[3,1]]
  • Output: -1
  • Explanation: No course can be studied because they are prerequisites of each other.

Constraints:

  • 1 <= n <= 5000
  • 1 <= relations.length <= 5000
  • relations[i].length == 2
  • 1 <= prevCourse_i, nextCourse_i <= n
  • prevCourse_i != nextCourse_i
  • All the pairs [prevCourse_i, nextCourse_i] are unique.

Solution⚓︎

class Solution {
public:
    int minimumSemesters(int n, vector<vector<int>>& relations) {
        vector<vector<int>> edges(n + 1);
        vector<int> inDegree(n + 1, 0);

        for (const auto& info : relations) {
            edges[info[0]].push_back(info[1]);
            inDegree[info[1]]++;
        }

        queue<int> que;
        for (int i = 1; i <= n; i++) {
            if (inDegree[i] == 0)
                que.push(i);
        }

        vector<int> cost(n + 1, 0);
        int res = 0, count = n;
        while (!que.empty()) {
            int current = que.front();
            que.pop();
            count--;

            cost[current]++;
            res = max(res, cost[current]);
            for (int v : edges[current]) {
                cost[v] = max(cost[v], cost[current]);
                if (--inDegree[v] == 0)
                    que.push(v);
            }
        }

        return count == 0 ? res : -1;
    }
};