Studious Amit and His New College
Practice
3.6 (10 votes)
Data structures
Depth first search
Easy
Graphs
Approved
Problem
57% Success 3244 Attempts 30 Points 1s Time Limit 256MB Memory 1024 KB Max Code

Amit has been awarded as the most meritorious student award in school. He is proud of it and decides to further improve his performance in his new college. He has to take N courses. The courses are labelled from 1 to N. Some courses might have prerequisites. For example, to take Data Structure course, one needs to take C Programming course first. There are M such pair denoting the course and it's corresponding prerequisite course which Amit needs to take first in order to successfully finish that particular course.

Given the number of courses he needs to take and a list of prerequisites pair, find out whether it is possible for Amit to finish all the courses and once again prove his mettle.

Input:

The first line of the input contains T denoting the number of test cases.

Each test case contains two non-negative integers N and M denoting the number of courses Amit needs to take and the number of prerequisites pair respectively.

Each of the next M lines contains two distinct positive integers \(u_{i}\) and \(v_{i}\) denoting the \(i^{th}\) prerequisite pair where \(u_{i}\) is a prerequisite for \(v_{i}\). It is ensured that the M lines will be pair-wise distinct.

Output:

For each test-case, output 1 if it is possible for Amit to finish all the courses or output 0 if Amit will not be able to complete all the courses.

Constraints:

  • \(1 \le T \le 5 \)
  • \( 1 \le N \le 10^{5}\)
  • \( 0 \le M \le 10^{5}\)
  • \( 1 \le u_{i}, v_{i} \le 10^{5}\)
  • \( u_{i} \ne v_{i} \)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
19 votes
Tags:
AlgorithmsDepth First SearchEasyGraphs
Points:30
58 votes
Tags:
AlgorithmsApprovedEasyGraphsOpen
Points:30
174 votes
Tags:
ApprovedDepth First SearchEasyGraphsOpen