Detect Cycle in Directed Graph

TCS NQT Coding Medium Go Ad-Free - ₹20/mo

Given a directed graph with V vertices (numbered from 1 to V) and E directed edges, determine if the graph contains at least one cycle. The graph is represented as a list of edges, where each edge is a pair [u, v] indicating a directed edge from vertex u to vertex v.

Examples:

Input: V=3, E=3, edges=[[1,2],[2,3],[3,1]]

Output: Yes

Explanation: The graph forms a cycle 1→2→3→1.

Input: V=4, E=3, edges=[[1,2],[2,3],[3,4]]

Output: No

Explanation: The graph is a linear chain with no cycles.

Input: V=5, E=5, edges=[[1,2],[2,3],[3,1],[4,5],[5,4]]

Output: Yes

Explanation: There are two cycles: one among vertices 1,2,3 and another among vertices 4,5.

Constraints

  • 1 ≤ V ≤ 1000
  • 0 ≤ E ≤ 10000
  • 1 ≤ u, v ≤ V for each edge