Skip to content

Latest commit

 

History

History

207

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return true if you can finish all courses. Otherwise, return false.

 

Example 1:

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

 

Constraints:

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.

Companies: Amazon, Google, Apple

Related Topics:
Depth-First Search, Breadth-First Search, Graph, Topological Sort

Similar Questions:

Solution 1. Topological Sort (BFS)

// OJ: https://leetcode.com/problems/course-schedule/
// Author: github.com/lzl124631x
// Time: O(V + E)
// Space: O(V + E)
class Solution {
public:
    bool canFinish(int n, vector<vector<int>>& E) {
        vector<vector<int>> G(n);
        vector<int> indegree(n);
        for (auto &e : E) {
            G[e[1]].push_back(e[0]);
            ++indegree[e[0]];
        }
        queue<int> q;
        for (int i = 0; i < n; ++i) {
            if (indegree[i] == 0) q.push(i);
        }
        while (q.size()) {
            int u = q.front();
            q.pop();
            --n;
            for (int v : G[u]) {
                if (--indegree[v] == 0) q.push(v);
            }
        }
        return n == 0;
    }
};

Solution 2. Topological Sort (DFS)

// OJ: https://leetcode.com/problems/course-schedule/
// Author: github.com/lzl124631x
// Time: O(V + E)
// Space: O(V + E)
class Solution {
public:
    bool canFinish(int n, vector<vector<int>>& E) {
        vector<vector<int>> G(n);
        for (auto &e : E) G[e[1]].push_back(e[0]);
        vector<int> state(n, -1); // -1 unvisited, 0 visiting, 1 visited
        function<bool(int)> dfs = [&](int u) -> bool {
            if (state[u] != -1) return state[u]; 
            state[u] = 0;
            for (int v : G[u]) {
                if (!dfs(v)) return false;
            }
            return state[u] = 1;
        };
        for (int i = 0; i < n; ++i) {
            if (!dfs(i)) return false;
        }
        return true;
    }
};