Cod sursa(job #3314245)

Utilizator Latyn76Tinica Alexandru Stefan Latyn76 Data 9 octombrie 2025 08:30:42
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

vector<int> a[100005];
int viz[100005];

// void bfs(int nod)
// {
//     queue<int> q;
//     q.push(nod);
//     cost[nod] = 0;
//     while (!q.empty())
//     {
//         int actNod = q.front();
//         q.pop();
//         for (auto next : a[actNod])
//             if (cost[next] > cost[actNod] + 1)
//             {
//                 cost[next] = cost[actNod] + 1;
//                 q.push(next);
//             }
//     }
// }

void dfs(int nod)
{
    viz[nod] = 1;
    for (auto w : a[nod])
    {
        if (!viz[w])
            dfs(w);
    }
}

int main()
{
    int n, m, s;
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    int cnt = 0;
    for (int i = 1; i <= n; i++)
    {
        if (viz[i] == 0)
        {
            dfs(i);
            cnt++;
        }
    }
    fout << cnt << '\n';
    return 0;
}