Cod sursa(job #2672222)

Utilizator MevasAlexandru Vasilescu Mevas Data 13 noiembrie 2020 14:56:33
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

vector<int> graph[100002];
vector<bool> visited;

void dfs(int start) {
    visited[start] = true;
    for (auto node : graph[start]) {
        if(!visited[node]) {
            dfs(node);
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;

    visited.resize(n + 1);

    for(int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;

        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    int componente = 0;
    for(int i = 1; i <= n; i++) {
        if (!visited[i]) {
            componente++;
            dfs(i);
        }
    }

    fout << componente;
}