Cod sursa(job #3376234)

Utilizator NemtoiAndreiNemtoi Gabriel Andrei NemtoiAndrei Data 16 noiembrie 2026 21:12:45
Problema Parcurgere DFS - componente conexe Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

vector<vector<int>> graph;
int N, M;
int viz[10001] = {0};
void dfs(int x)
{
    viz[x] = 1;
    for (auto &i : graph[x])
    {
        if (viz[i] == 0)
        {
            dfs(i);
        }
    }
}
int main()
{
    fin >> N >> M;
    int comp = 0;
    graph.resize(N + 1);
    for (int i = 0; i < M; i++)
    {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    for (int i = 1; i <= N; i++)
        if (viz[i] == 0)
        {
            dfs(i);
            comp += 1;
        }

    fout << comp;
    return 0;
}