Detect Cycle in a Directed Graph

Determine if a given directed graph contains a cycle. Your function should return true if the graph contains at least one cycle, and false otherwise.

Input:

The first line of input contains an integer T, representing the number of test cases.
The first line of each test case consists of two integers, V and E. V represents the number of vertices, and E represents the number of edges in the graph.
The next E lines for each test case describe the edges of the graph, where each edge is given by two integers A and B, indicating a directed edge from vertex A to vertex B.

Output:

For each test case, print "true" if a cycle exists in the graph, otherwise print "false".

Example:

Input:
2
3 3
0 1
1 2
2 0
4 3
0 1
1 2
2 3
Output:
true
false

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ V ≤ 10^3
  • 0 ≤ E ≤ 10^3
  • 0 ≤ A, B < V

Time Limit: 1 sec

AnswerBot
11d

Detect cycle in a directed graph and return true if cycle exists, false otherwise.

  • Use Depth First Search (DFS) to detect cycles in the directed graph.

  • Maintain a visited array to keep track of visited ...read more

Help your peers!
Add answer anonymously...
Amazon Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter