Cod sursa(job #3314501)

Utilizator LucaSerbanLuca Serban LucaSerban Data 10 octombrie 2025 10:43:27
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>

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

int n, m, cont;

void listadeadiacenta(std::vector<std::vector<int>>& G, bool isOriented)
{
    int x, y;
    for (int i = 0; i < m; ++i) {
        in >> x >> y;
        if (isOriented) {
            G[x].push_back(y);
        } else {
            G[x].push_back(y);
            G[y].push_back(x);
        }
    }
}

void DFS(std::vector<std::vector<int>>& G, std::vector<bool>& visited, int current)
{
    visited[current] = true;
    for (auto neighbor : G[current])
    {
        if (!visited[neighbor])
        {
            DFS(G, visited, neighbor);
        }
    }
}

int main()
{
    in >> n >> m;
    std::vector <std::vector <int> > G(n + 1);
    std::vector <bool> visited(n + 1);
    listadeadiacenta(G, false);
    for (int i = 1; i <= n; i++)
        if (!visited[i])
            DFS(G, visited, i), cont++;
    out << cont << '\n';
}