You are given an undirected graph with V vertices and its adjacency list. Your task is to determine whether the graph contains a cycle using Depth First Search (DFS).
Return true if a cycle exists; otherwise, return false.
Input: V = 3, edges = [[0,1],[1,2],[2,0]]
Output: true
Explanation: The graph contains a cycle.
Input: V = 4, edges = [[0,1],[1,2],[2,3]]
Output: false
Explanation: The graph does not contain any cycle.
Input: V = 1, edges = []
Output: false
Explanation: A graph with one vertex cannot contain a cycle.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
3 3 0 1 1 2 2 0
true
4 4 0 1 1 2 2 3 3 0
true