Cod sursa(job #3227276)

Utilizator Gergo123Schradi Gergo Gergo123 Data 29 aprilie 2024 09:43:34
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

void dfs(
    int v,
    const vector<vector<int>> &adj,
    vector<bool> &visited)
{
    visited[v] = true;

    int nsz = adj[v].size();
    for (int i = 0; i < nsz; i++) {
        int sz = adj[v][i];
        if (!visited[sz])
            dfs(sz, adj, visited);
    }
}

int main()
{
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");
    int n, m;
    fin >> n >> m;
    vector<vector<int>> adj(n+1);
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    vector<bool> visited(n+1, false);
    int hany_komp = 0;
    for (int v = 1; v <= n; v++)
        if (!visited[v]) {
            ++hany_komp;
            dfs(v, adj, visited);
        }
    fout << hany_komp << endl;
    return 0;
}