# 210. Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example 1:

Input: 2, [[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: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [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] .

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

# Solution

Approach 1: BFS -- use the indegree method to find a linearization of the nodes.

Approach 2: DFS -- build directed graph, dfs on all nodes, and output a POST order traversal.

# Code (Python)

Approach 1:

        # BFS idea: use the indegree method to find a linearization of the nodes
        edges = {course: [] for course in range(numCourses)}
        indegree = {course: 0 for course in range(numCourses)}
        layer = set([course for course in range(numCourses)])
        for course, prereq in prerequisites:
            # prereq -> [advanced1, advanced2...]
            edges[prereq].append(course)
            indegree[course] += 1
            if course in layer:
                layer.remove(course)
        
        ordering = []
        layer = deque(layer)
        while layer:
            course = layer.popleft()
            ordering.append(course)
            for neighbor in edges[course]:
                indegree[neighbor] -= 1
                if indegree[neighbor] == 0:
                    layer.append(neighbor)
        
        if len(ordering) == numCourses:
            return ordering
        return []

Approach 2:

    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        # DFS idea: build directed graph (course -> prereq), dfs on all nodes, and output a POST order traversal
        edges = {course: [] for course in range(numCourses)}
        for course, prereq in prerequisites:
            # course -> [prereq1, prereq2, ...]
            edges[course].append(prereq)
        
        ordering = []
        status = {course: -1 for course in range(numCourses)}
        for course in range(numCourses):
            if not self._search(course, status, edges, ordering):
                return []
        return ordering
    
    def _search(self, node, status, edges, ordering):
        if status[node] == 0:
            return False
        if status[node] == 1:
            return True

        status[node] = 0
        for neighbor in edges[node]:
            if not self._search(neighbor, status, edges, ordering):
                return False
        ordering.append(node)
        status[node] = 1
        return True

# Code (C++)

Approach 1:

// BFS
class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        unordered_map<int, int> indegree;
        unordered_map<int, vector<int>> outNodes;
        for (int i = 0; i < numCourses; ++i)
        {
            indegree[i] = 0;
        }
        for (auto it : prerequisites)
        {
            int curr = it.first;
            int prev = it.second;
            indegree[curr]++;
            outNodes[prev].push_back(curr);
        }
        vector<int> order;
        while (!empty(indegree))
        {
            unordered_map<int, int>::iterator it;
            for (it = indegree.begin(); it != indegree.end(); ++it)
            {
                if (it->second == 0)
                    break;
            }
            if (it == indegree.end())
                return vector<int>();
            int prev = it->first;
            indegree.erase(it);
            order.push_back(prev);
            for (auto curr : outNodes[prev])
            {
                indegree[curr]--;
            }
        }
        return order;
    }
};

Approach 2:

// DFS
class Solution {
private:
    unordered_map<int,vector<int>> neighbors;
    vector<bool> visitedPerm;
    vector<bool> visitedTemp;
    vector<bool> cycling;
    vector<int> order;
    bool canFinishCourse(int course) {
        if (visitedPerm[course])
            return !cycling[course];
        if (visitedTemp[course])
            return false;
        visitedTemp[course] = true;
        for (auto prev : neighbors[course])
        {
            if (!canFinishCourse(prev))
            {
                cycling[course] = true;
                break;
            }
        }
        visitedTemp[course] = false;
        visitedPerm[course] = true;
        if (!cycling[course])
            order.push_back(course);
        return !cycling[course];
    }
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        for (auto pair : prerequisites)
        {
            neighbors[pair[0]].push_back(pair[1]);
        }
        visitedPerm = vector<bool>(numCourses, false);
        visitedTemp = vector<bool>(numCourses, false);
        cycling = vector<bool>(numCourses, false);
        for (int i = 0; i < numCourses; ++i)
        {
            if (!canFinishCourse(i))
                return vector<int>();
        }
        return order;
    }
};