Cycle Detection in a Directed Graph

Determine if a given directed graph contains a cycle. Return true if at least one cycle is found, otherwise return false.

Input:

T
The first line consists of the integer T, representing the number of test cases.
For each test case, the first line contains two integers V and E.
V is the number of vertices, and E is the number of edges.
The next E lines each comprise two space-separated integers A and B, indicating a directed edge from vertex A to vertex B.

Output:

For every test case, output "true" if a cycle exists in the graph, otherwise show "false".

Example:

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

Explanation: The graph depicted in the example above includes a cycle involving the vertices represented by the edges (1,2), (2,3), and (3,1).

Constraints:

  • 1 <= T <= 10
  • 1 <= V <= 10^3
  • 0 <= E <= 10^3
  • 0 <= A, B < V
  • Time Limit: 1 sec
AnswerBot
2d

Detect if a directed graph contains a cycle.

  • Use depth-first search (DFS) to detect cycles in the graph.

  • Maintain a visited array to keep track of visited vertices.

  • If a vertex is visited again during DF...read more

Help your peers!
Add answer anonymously...
PayPal Software Engineer 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