Cod sursa(job #3269512)

Utilizator vladm98Munteanu Vlad vladm98 Data 19 ianuarie 2025 14:15:29
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");
// vector <int> - un tip de date

vector <int> graph[100005]; // graph[i] - vector <int>
// int graph[100005]; // graph[i] - int
// graph[1] - este un vector <int> si va contine toti vecinii lui 1 - initia este gol

int visited[100005];

void dfs(int node) {
    visited[node] = 1; // vizitam nodul curent pentru a nu intra in el din nou

    // for (int i = 0; i < graph[node].size(); ++i) x = graph[node][i];
    for (auto x : graph[node]) {
        if (visited[x]) continue;
        dfs(x);
    }
}

int main()
{
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;

        graph[x].push_back(y); // pushez nodul y in lista de vecini ai lui x
        graph[y].push_back(x); // pushez nodul x in lista de vecini ai lui y pentru ca graful este neorientat
    }
    int counter = 0;

    for (int i = 1; i <= n; ++i) {
        if (visited[i]) continue;
        dfs(i);
        ++counter;
    }

    fout << counter;
    return 0;
}