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] = [a`

this means you must take the course_{i}, b_{i}]`b`

before the course_{i}`a`

. Given the total number of courses_{i}`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, returnanyof them. If it is impossible to finish all courses, returnan empty array.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].

This explains a very important programming interview concept which is based on graph algorithm and is known as topological sort.This is a very important concept for solving graph problems based on ordering.We can find the topological sort using the simple DFS along with a STACK.Topological sort for a graph is only possible if it is a directed acyclic graph (DAG).I have explained the entire algorithm by taking proper examples and have also shown the code implementation using a problem course schedule 2 which is from leetcode #210.I have shown the code walk through at the end of the video. CODE is present below as usual.

class Solution { //Graph coloring: 0->not visited...1->visited...2->visited & processed bool detectCycle_util(vector<vector<int>>& adj,vector<int>& visited,int v) { if(visited[v]==1) return true; if(visited[v]==2) return false; visited[v]=1; //Mark current as visited for(int i=0;i<adj[v].size();++i) if(detectCycle_util(adj,visited,adj[v][i])) return true; visited[v]=2; //Mark current node as processed return false; } //Cycle detection bool detectCycle(vector<vector<int>>& adj,int n) { vector<int> visited(n,0); for(int i=0;i<n;++i) if(!visited[i]) if(detectCycle_util(adj,visited,i)) return true; return false; } //Topological sort void dfs(vector<vector<int>>& adj,int v,vector<bool>& visited,stack<int>& mystack) { visited[v] = true; for(int i=0;i<adj[v].size();++i) if(!visited[adj[v][i]]) dfs(adj,adj[v][i],visited,mystack); mystack.push(v); } public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { int n=prerequisites.size(); vector<vector<int>> adj(numCourses); //Make adjacecncy list for(int i=0;i<n;++i) adj[prerequisites[i][1]].push_back(prerequisites[i][0]); //Detect CYCLE...If present then return empty array vector<int> ans; if(detectCycle(adj,numCourses)) return ans; //Find toposort and store it in stack stack<int> mystack; vector<bool> visited(numCourses,false); //Apply DFS and find topological sort for(int i=0;i<numCourses;++i) if(!visited[i]) dfs(adj,i,visited,mystack); while(!mystack.empty()) { ans.push_back(mystack.top()); mystack.pop(); } return ans; } };

## One Reply to “Topological sort | Course schedule 2 | Leetcode #210”