cppAcademy
← Back to the DFS lesson

Connected Components

BeginnerDFS 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

An undirected graph has N vertices numbered from 1 to N and M edges. A connected component is a maximal group of vertices in which every vertex can reach every other vertex. Determine the number of connected components. An isolated vertex is a component by itself. Self-loops and repeated edges are allowed and do not change connectivity.

Input format

The first line contains N and M. The next M lines contain U and V, describing an undirected edge.

Output format

Print one integer: the number of connected components.

Constraints

  • 1 ≤ N ≤ 100000
  • 0 ≤ M ≤ 200000
  • 1 ≤ U, V ≤ N

Sample input

6 3
1 2
2 3
4 5

Sample output

3

Sample explanation

The components are {1, 2, 3}, {4, 5}, and {6}. Start a traversal at each vertex that has not already been visited.

Need a hint?

A traversal visits exactly one component. Remember to check every vertex, including isolated vertices. An iterative DFS avoids call-stack overflow on long chains.

Review Depth-first search →