Suppose, you want to enter into a well-known computer science university, but they always test students before giving admission. Now it is your turn, they give you a long list of pairs of courses. Each pair $(\text{course}A,\text{courseB})$ is representing that, completing the $\text{courseA}$ is a prerequisite for the $\text{courseB}$.
Now the challenge is that, they will give you two courses, $\text{courseX}$ and $\text{courseY}$. And you have to find out whether $\text{courseX}$ can be done before $\text{courseY}$.
The main twist is, the list is very large, so you can not remember everything. They are smart, so they have given you course names which are not computer science courses.
Well, this problem can be solved by converting it to a graph where vertices are courses and directed edges representing prerequisites. Then find out the topological sort of the graph and you are done!!
Topological Sort is the sorting of the vertices in such a way that, for any two vertices $a$ and $b$, if there is a directed edge from $a \to b$ then $a$ must appear before $b$ in the topological ordering.
See that the vertices having indegree $0$ are appearing first in the ordering. But what next? What if we remove both the vertices and all the edges coming out from it?
See now, $c$ is the vertex having $0$ indegree, which is appearning next in the ordering.
And what if we remove $c$ and all the edges coming out from it. The next $0$ indegree vertices are $d$ and $e$, which are the next vertices in the ordering.
Now, we have seen the approach using modified BFS. Can we use DFS as well?
Yes, we can use DFS with some modification.
Here, we will start DFS from an arbitrary vertex-$U$ and first visit all the adjacent vertices by recursively calling DFS on all of them and then at the end, add U at the front of the topological order.
What does it do?
This thing makes sure that all the vertices which are dependent on U will appear after U, because we are adding U at the front of the ordering.
## Algorithm using DFS
1. Mark all the vertices as unvisited.
2. Choose any unvisited vertex and start a DFS start from it (say $V$).
3. Inside DFS, Mark $V$ as visited and loop over the adjacent vertices of $V$.
4. Recursivly call DFS on all the unvisited adjacent vertices.
5. As all the DFS calls completes, add $V$ at the front(head) of the topological order.
6. If there is an unvisited vertex then go to the step 2, else stop.
**Note:** You can take linked list to store the topological order, which is empty at the starting of the algorithm.
**Visualization:**
```c++
#include <bits/stdc++.h>
using namespace std;
#define MAX_DIST 100000000
void dfs(vector<vector<int> > &graph, int start, list<int>&linked_list, vector<bool>& visited)