
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)
Editorial
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. | ||||
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