Cod sursa(job #3122218)

Utilizator cavalerulNegruCavalerul Negru cavalerulNegru Data 17 aprilie 2023 21:30:46
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <iostream>
#include <vector>

#define nmax 100005

using namespace std;

vector<int> graph[nmax];
int n, m;


void dfs(int node, vector<int> &viz){

    viz[node] = 1;
    for(auto it : graph[node]){
        if( !viz[it] ){
            dfs(it,viz);
        }
    }
    
}

int main(){

    ifstream f("dfs.in");
    ofstream g("dfs.out");

    int x, y, sol = 0;
    f >> n >> m;

    vector<int> viz(n + 1,0);
    for(int i = 0; i < m; i++){

        f >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);

    }

    for(int i = 1; i <= n; i++){
        if(!viz[i]){
           dfs(i,viz);
           sol++;
        }
    }
    g << sol << "\n";
}