Cod sursa(job #3317184)

Utilizator antoniogrosuAntonio Grosu antoniogrosu Data 22 octombrie 2025 17:14:38
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");
/// dfs

/// DFS(nod)
///     vis[nod] = 1
///     for x e apartine L[nod]
//      // if vis[x]==0
///         //DFS(x)

vector<vector<int>> L;
vector<int> vis;

void dfs(int x)
{
    vis[x] = 1;
    for (int i = 0; i < L[x].size(); i++)
        if (vis[L[x][i]] == 0)
            dfs(L[x][i]);
}

int main()
{

    int n, m, nr = 0;

    in >> n >> m;

    L.resize(n + 1, vector<int>());
    vis.resize(n + 1);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    for (auto i = 1; i <= n; i++)
    {
        if (vis[i] == 0)
        {
            nr++;
            dfs(i);
        }
    }

    out << nr;
    return 0;
}