Cod sursa(job #2501747)

Utilizator AntoniuFicAntoniu Ficard AntoniuFic Data 30 noiembrie 2019 10:06:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int n, m, bodies;
vector<int> graph[100005];
int b[100005];

void dfs(int node){
    for(auto &v : graph[node]){
        if(b[v] == 0){
            b[v] = bodies;
            dfs(v);
        }
    }
}

int main() {
    ifstream f("dfs.in");
    ofstream g("dfs.out");
    f>>n>>m;
    for (int i = 0; i < m; ++i) {
        int node, destination;
        f>>node>>destination;
        graph[node - 1].push_back(destination - 1);
        graph[destination - 1].push_back(node - 1);
    }
    for (int i = 0; i < n; ++i) {
        if(b[i] == 0){
            ++bodies;
            dfs(i);
        }
    }
    g<<bodies;
    return 0;
}