DMOJ · graph2p1

Connected Components

This C++ solution uses graph traversal for DMOJ graph2p1 Connected Components. Read the reasoning, inspect the code, or try your own test case below.

graph2p1Graphs & treesGraph traversalC++49 lines
Solution052of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Connected Components supplies an undirected adjacency matrix and asks to list sorted components; the code traverses and prints them.

Graphs & trees

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

connected_components.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    vector<vector<int>> adj, components;
    vector<bool> visited;
     
    void dfs(int u, vector<int>& comp){
        visited[u] = true;
        comp.push_back(u + 1); // 1 based index
        for(int v : adj[u]){
            if(!visited[v]){
                dfs(v, comp);
            }
        }
    }
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        int n;
        cin >> n;
        adj.resize(n); visited.resize(n);
     
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                int c;
                cin >> c;
                if(c == 1){
                    adj[i].push_back(j); // add edge from node i to j
                }
            }
        }
        for(int i = 0; i < n; i++){
            if(!visited[i]){
                vector<int> comp;
                dfs(i, comp);
                sort(comp.begin(), comp.end());
                components.push_back(comp);
            }
        }
        sort(components.begin(), components.end());
        for(auto &comp : components){
            for(int node : comp){
                cout << node << " ";
            }
            cout << '\n';
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.