## Kahn’s algorithm | Topological sort | Course schedule 2 | Leetcode #210

Find the topological sort of a given graph. Here, i have explained how to find topological sort using Kahn’s algorithm.This algorithm is based on BFS (Breadth first search) and makes use of QUEUE and an Indegree ARRAY.Topological sort can also be found recursively using DFS (Depth first search) and a STACK which i have explained in my previous video.I have shown all the steps of this algorithm clearly using proper examples and have also shown the solution for a practice problem from leetcode number 210 which is course schedule 2.I have dry run the algorithm and have also explained the code walk through at the end of the video.CODE LINK is present below as usual.

In this tutorial we will solve the Course Schedule 2 problem from leetcode to understand Kahn’s Algorithm properly.

```class Solution {
//Graph coloring: 0->not visited...1->visited...2->visited & processed
{
if(visited[v]==1)
return true;
if(visited[v]==2)
return false;

visited[v]=1;   //Mark current as visited
return true;

visited[v]=2;   //Mark current node as processed
return false;
}

//Cycle detection
{
vector<int> visited(n,0);
for(int i=0;i<n;++i)
if(!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;

mystack.push(v);
}
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
int n=prerequisites.size();
for(int i=0;i<n;++i)

//Detect CYCLE...If present then return empty array
vector<int> ans;
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])