Cod sursa(job #3122710)

Utilizator alexlazuLazureanu Alexandru Ioan alexlazu Data 20 aprilie 2023 10:26:27
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.73 kb
#include <bits/stdc++.h>
#include <fstream>

using namespace std;

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

int n, m;

void dfs(vector<vector<int>> & adj, vector<bool> &viz, int node, int components) {
    viz[node] = true;
    for (auto neigh : adj[node]) {
        if (!viz[neigh])
            dfs(adj, viz, neigh, components);
    }
}

int main() {
    in >> n >> m;
    vector<vector<int>> adj(n + 1, vector<int>());
    vector<bool> viz(n + 1, 0);

    for (int i = 1, x, y; i <= m; i++) {
        in >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    int components = 0;

    for (int i = 1; i <= n; i++) {
        if (!viz[i])
            dfs(adj, viz, i, ++components);
    }

    out << components;
}