Cod sursa(job #3124038)

Utilizator gazpircegaz pirce gazpirce Data 26 aprilie 2023 18:49:49
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream in("dfs.in");

ofstream out("dfs.out");

const int MAXN = 100005;

int n, m;
vector<int> g[MAXN];
bool visited[MAXN];

void dfs(int node, vector<int>& component) {
    visited[node] = true;
    component.push_back(node);
    for (int i = 0; i < g[node].size(); i++) {
        int nextNode = g[node][i];
        if (!visited[nextNode]) {
            dfs(nextNode, component);
        }
    }
}

int main() {
    in >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        in >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    int nr_comp = 0;

    for (int i = 1; i <= n; i++) {
        if (!visited[i]) {
            vector<int> component;
            dfs(i, component);
            nr_comp++;
        }
    }

    out << nr_comp << endl;

    return 0;
}