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 integersV
andE
.
V is the number of vertices, and E is the number of edges.
The next E lines each comprise two space-separated integersA
andB
, indicating a directed edge from vertexA
to vertexB
.
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...
Top PayPal Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Top HR questions asked in PayPal Software Engineer
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app