Algorithm


Problem Name: 210. Course Schedule II

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 the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

 

Example 1:

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

Example 2:

Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].

Example 3:

Input: numCourses = 1, prerequisites = []
Output: [0]

 

Constraints:

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • ai != bi
  • All the pairs [ai, bi] are distinct.

Code Examples

#1 Code Example with C Programming

Code - C Programming


int has_cycle(int *buff, int n, int sz, int *visited) {
    int i, *node;
    
    if (visited[n] == -1) return 0;
    if (visited[n] == 1) return 1;
    
    visited[n] = 1;
    
    node = &buff[n * sz];
    for (i = 0; i  <  sz; i ++) {
        if (node[i] != 0 && has_cycle(buff, node[i], sz, visited)) {
            return true;
        }
    }
    
    visited[n] = -1;
    
    return false;
}
void dfs(int *buff, int n, int sz, int *indegree, int *visited, int *courses, int *k) {
    int i, *node;
    
    visited[n] = 3;
    
    courses[(*k) ++] = n - 1;
    
    node = &buff[n * sz];
    for (i = 0; i  <  sz; i ++) {
        n = node[i];
        if (n && visited[n] != 3) {
            indegree[n] --;
            if (indegree[n] == 0) {
                dfs(buff, n, sz, indegree, visited, courses, k);
            }
        }
    }
}
int* findOrder(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int* returnSize) {
    int *buff, *root, *node_a;
    int i, n, k, a, b;
    int *visited;
    int *indegree;
    int *courses;
    
    buff = calloc((numCourses + 1) * numCourses, sizeof(int)); // each node with all possible neighbors
    visited = calloc((numCourses + 1), sizeof(int));
    indegree = calloc((numCourses + 1), sizeof(int));
    courses  = calloc(numCourses, sizeof(int));
    
    root = &buff[0];  // root node has neighbors of all
    for (i = 0; i  <  numCourses; i ++) {
        root[i] = i + 1;
    }
    
    for (i = 0; i  <  prerequisitesRowSize; i ++) {
        a = prerequisites[i][1];
        b = prerequisites[i][0];
        node_a = &buff[(a + 1) * numCourses];
        node_a[b] = (b + 1);    // node a has neighbor b which has id b + 1
        indegree[(b + 1)] ++;
    }
    
    k = 0;
    
    for (i = 0; i  <  numCourses; i ++) {
        n = root[i];
        if (indegree[n] == 0 && visited[n] != 3) {
            dfs(buff, n, numCourses, indegree, visited, courses, &k);
        }
    }
    
    if (k != numCourses) k = 0;
    
done:
    free(buff);
    free(visited);
    free(indegree);

    *returnSize = k;
    
    return courses;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
numCourses = 2, prerequisites = [[1,0]]

Output

x
+
cmd
[0,1]

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    vector<int> findOrder(int numCourses, vector < pair<int, int>>& prerequisites) {
        vector<int>res;
        vector<int>indegree(numCourses);
        vector < vector<int>>graph(numCourses);
        for(auto p: prerequisites){
            graph[p.second].push_back(p.first);
            indegree[p.first]++;
        }
        for(int i = 0; i  <  numCourses; i++){
            int j = 0;
            for(; j  <  numCourses; j++) if(indegree[j] == 0) break;
            if(j == numCourses) return vector<int>();
            indegree[j] = -1;
            for(auto x: graph[j]) indegree[x]--;
            res.push_back(j);
        }
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
numCourses = 2, prerequisites = [[1,0]]

Output

x
+
cmd
[0,1]

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int[] findOrder(int numCourses, int[][] prerequisites) {
    Map();
    int[] prerequisiteCount = new int[numCourses];
    for (int[] prerequisite : prerequisites) {
      prerequisiteToCourseDependency.computeIfAbsent(prerequisite[1], k -> new ArrayList < >())
        .add(prerequisite[0]);
      prerequisiteCount[prerequisite[0]]++;
    }
    Queue < Integer> queue = new LinkedList<>();
    for (int i = 0; i  <  numCourses; i++) {
      if (prerequisiteCount[i] == 0) {
        queue.add(i);
      }
    }
    int[] courseOrder = new int[numCourses];
    int courseOrderIdx = 0;
    while (!queue.isEmpty()) {
      int course = queue.remove();
      courseOrder[courseOrderIdx++] = course;
      for (Integer dependentCourse : prerequisiteToCourseDependency.getOrDefault(course, new ArrayList < >())) {
        prerequisiteCount[dependentCourse]--;
        if (prerequisiteCount[dependentCourse] == 0) {
          queue.add(dependentCourse);
        }
      }
    }
    return courseOrderIdx == numCourses ? courseOrder : new int[]{};
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]

Output

x
+
cmd
[0,2,1,3]

#4 Code Example with Javascript Programming

Code - Javascript Programming


const findOrder = function(numCourses, prerequisites) {
  const graph = {}, inDegree = Array(numCourses).fill(0)
  for(const [s, e] of prerequisites) {
    inDegree[s]++
    if(graph[e] == null) graph[e] = []
    graph[e].push(s)
  }
  
  const res = []
  let q = []
  for(let i = 0; i < numCourses; i++) {
    if(inDegree[i] === 0) q.push(i)
  }
  
  while(q.length) {
    const nxt = []
    for(let i = 0; i  <  q.length; i++) {
      const cur = q[i]
      res.push(cur)
      for(const e of (graph[cur] || [])) {
        inDegree[e]--
        if(inDegree[e] === 0) nxt.push(e>
      }
    }
    q = nxt
  }
  
  return res.length === numCourses ? res : []
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]

Output

x
+
cmd
[0,2,1,3]

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def findOrder(self, numCourses, prerequisites):
        children, parent = collections.defaultdict(set), collections.defaultdict(set)
        for i, j in prerequisites: children[i].add(j); parent[j].add(i)
        stack = [i for i in range(numCourses) if not children[i]]
        for i in stack:
            for j in parent[i]:
                children[j].remove(i)
                if not children[j]: stack += j,
        return stack if len(stack) == numCourses else []
Copy The Code & Try With Live Editor

Input

x
+
cmd
numCourses = 2, prerequisites = [[1,0]]

Output

x
+
cmd
[0,1]

#6 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0210_CourseSchedule
    {
        public int[] CanFinish(int numCourses, int[][] prerequisites)
        {
            var adj = new bool[numCourses, numCourses];
            BuildGraph(adj, prerequisites);

            var visited = new int[numCourses];
            var result = new List < int>();
            for (int i = 0; i  <  numCourses; i++)
                if (visited[i] == 0 && !DFS(adj, visited, i, numCourses, result)) return new int[] { };

            result.Reverse();
            return result.ToArray();
        }

        private bool DFS(bool[,] adj, int[] visited, int i, int numCourses, IList < int> result)
        {
            visited[i] = 1;
            for (int j = 0; j  <  numCourses; j++)
            {
                if (adj[i, j])
                {
                    if (visited[j] == 1) return false;
                    if (visited[j] == 0)
                        if (!DFS(adj, visited, j, numCourses, result)) return false;
                }
            }

            visited[i] = 2;
            result.Add(i);
            return true;
        }

        private void BuildGraph(bool[,] adj, int[][] prerequisites)
        {
            foreach (var prerequisite in prerequisites)
                adj[prerequisite[1], prerequisite[0]] = true;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
numCourses = 2, prerequisites = [[1,0]]

Output

x
+
cmd
[0,1]
Advertisements

Demonstration


Previous
#209 Leetcode Minimum Size Subarray Sum Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#211 Leetcode Design Add and Search Words Data Structure Solution in C, C++, Java, JavaScript, Python, C# Leetcode