

There is no limitation on taking the number of courses in a particular semester as long as all the prerequisites for taking the course are satisfied.
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.
The first line of each test case contains two integers ‘N’ and ‘M,’ which denotes the number of courses and the number of rows of the matrix ‘prerequisites.’
The next M lines contain two integers, prerequisites[i][0] and prerequisites[i][1], denoting that prerequisites[i][0] has to be studied before prerequisites[i][1].
For each test case, print the minimum number of semesters required to study all the courses.
Print the output of each test case in a separate line.
1<= T <= 50
1 <= N <= 20000
0 <= M <= 20000
1 <= prerequisites[i][0], prerequisites[i][1] <= N
prerequisites[i][0] != prerequisites[i][1], for any valid i
Time Limit: 1 sec
The idea is to represent the given prerequisites as a directed graph and then use topological sorting to find the minimum number of semesters.
To construct the graph, we can use an array of an unordered set of integers. The indexes will represent the course and the values in the unordered set will represent the courses for which the key is a prerequisite. After that, find the indegree of every vertex and will do a Breadth-first Search. Indegree of a vertex is the number of edges from any vertex to the given vertex. Whenever we visit a vertex, we will reduce the in-degree of all its connected vertices by 1. If the in-degree of a vertex becomes 0, it means that the vertex can be taken in the particular semester and all the prerequisites for this course are already satisfied.
The steps are as follows: