Course Schedule II - Medium - NL

1 minute read

Published:

Question

  • https://leetcode.com/problems/course-schedule-ii/

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

Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.

Given the total number of courses numCourses and a list of the prerequisite pairs, 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.

Approach

  • Topo sort + cycle detection

Solution

class Solution {
public:
    
    void dfs(vector<vector<int>>& adj, vector<bool> &vis, vector<bool> &rec, int i, bool &ans, vector<int> &result){
      vis[i]=true;
      rec[i]=true;
      for(int j=0;j<adj[i].size();j++){
          if(!vis[adj[i][j]]){
              dfs(adj, vis, rec, adj[i][j], ans, result);
          }
          if(rec[adj[i][j]]){
              ans=false;
          }
      } 
      result.push_back(i);
      rec[i]=false;
    }
    
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
        vector<vector<int> > adj;
        vector<bool> vis;
        vector<bool> rec;
        vector<int> result;
        for(int i=0;i<numCourses;i++){
            vector<int> t;
            adj.push_back(t);
            vis.push_back(false);
            rec.push_back(false);
        }
        for(int i=0;i<prerequisites.size();i++){
            adj[prerequisites[i][1]].push_back(prerequisites[i][0]);
        }
        bool ans = true;
        for(int i=0;i<numCourses;i++){
            if(!vis[i]){
                dfs(adj, vis, rec, i, ans, result);
            }
        }
        if (ans == false) {
            vector<int> result1;
            return result1;
        }
        int h = result.size();
        for(int i=0; i<h/2; i++) {
            int temp = result[h-1-i];
            result[h-1-i] = result[i];
            result[i] = temp;
        }
        return result;
    }
};