Cod sursa(job #3244028)

Utilizator lolismekAlex Jerpelea lolismek Data 23 septembrie 2024 01:15:16
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 1e5;

bool viz[NMAX + 1];
vector <int> adj[NMAX + 1];

void dfs(int node){
    viz[node] = 1;
    for(int vec : adj[node]){
        if(!viz[vec]){
            dfs(vec);
        }
    }
}

int main(){

    int n, m;
    fin >> n >> m;
    
    for(int i = 1; i <= m; i++){
        int a, b;
        fin >> a >> b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    
    int nrComp = 0;
    for(int i = 1; i <= n; i++){
        if(!viz[i]){
            nrComp += 1;
            dfs(i);
        }
    }
    
    fout << nrComp << '\n';

    return 0;
}