cppAcademy
← Back to the DFS lesson

Cycle Detection

AdvancedDFS practice · C++17Best score: not submitted

Client-side educational grading. Submit runs your C++17 program against ten predefined tests in your browser. Tests are intentionally visible through See Hidden Tests. Scores are local practice records, not secure competition results.

main.cpp · C++17

Loading Monaco Editor…

Loading this problem’s draft…

Ctrl / ⌘ + Enter runs your custom test. Input limit: 1 MiB.

Loading editor…

Standard Output

Standard Error

Compiler Diagnostics

Submission results

Ten tests, ten points each. Find a Path accepts any valid path. Custom runs never change your score.

Each test has a 5-second execution limit, 256 MiB linked program WASM memory maximum, and 1 MiB combined output limit. Allocated WASM memory is not peak browser memory. Deep recursive DFS can overflow the WASM stack; an explicit stack is safer for long paths.

Problem statement

Given a simple undirected graph with N vertices numbered from 1 to N and M edges, determine whether it contains a cycle. Simple means that there are no self-loops and no duplicate undirected edges. A cycle has at least three distinct vertices, with consecutive vertices and the first and last vertices connected by edges. The graph may be disconnected.

Input format

The first line contains N and M. Each of the next M lines contains the two distinct endpoints U and V of an edge. Every undirected edge appears at most once.

Output format

Print YES if any component contains a cycle. Otherwise, print NO.

Constraints

  • 1 ≤ N ≤ 100000
  • 0 ≤ M ≤ min(200000, N(N−1)/2)
  • 1 ≤ U, V ≤ N; U ≠ V
  • No duplicate undirected edges

Sample input

4 4
1 2
2 3
3 1
3 4

Sample output

YES

Sample explanation

Vertices 1, 2, and 3 form the cycle 1–2–3–1. The edge to vertex 4 is not part of the cycle.

Need a hint?

In an undirected DFS, the edge to the parent is not evidence of a cycle. Explore every connected component. Use an iterative traversal if a deep recursive call stack is unsafe.

Review Depth-first search →