Tutorialspoint
Problem
Solution
Submissions

Check if a Graph Has a Cycle

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to detect if an undirected graph has a cycle. Implement a method that takes the number of vertices and edges of a graph as input and determines whether the graph contains at least one cycle.

Example 1
  • Input:
    • Number of vertices: 5
    • Edges: [[0,1], [1,2], [2,3], [3,4]]
  • Output: false
  • Explanation:
    • The given graph is a simple path from vertex 0 to 4 with no cycles.
Example 2
  • Input:
    • Number of vertices: 5
    • Edges: [[0,1], [1,2], [2,0], [3,4]]
  • Output: true
  • Explanation:
    • The vertices 0, 1, and 2 form a cycle (0-1-2-0).
Constraints
  • 1 ≤ number of vertices ≤ 1000
  • 0 ≤ number of edges ≤ 3000
  • All vertices are numbered from 0 to n-1
  • No self-loops or multiple edges between the same pair of vertices
  • Time Complexity: O(V+E) where V is the number of vertices and E is the number of edges
  • Space Complexity: O(V)
GraphKPMGTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • You can use either Depth-First Search (DFS) or Breadth-First Search (BFS)
  • Track visited vertices to avoid processing the same vertex multiple times
  • For undirected graphs, you need to keep track of the parent vertex to avoid false cycle detection
  • If a vertex is already visited and not the parent of the current vertex, a cycle exists
  • Implement the graph using an adjacency list for efficient traversal

Steps to solve by this approach:

 Step 1: Create an adjacency list representation of the graph.

 Step 2: Initialize a boolean array to keep track of visited vertices.
 Step 3: For each unvisited vertex, perform a DFS traversal.
 Step 4: During DFS, mark the current vertex as visited.
 Step 5: For each adjacent vertex, if it's not visited, recursively call DFS.
 Step 6: If an adjacent vertex is already visited and not the parent of the current vertex, a cycle exists.
 Step 7: If no cycle is found after checking all vertices, return false.

Submitted Code :