Cod sursa(job #3336521)

Utilizator SomethingAndrei Marian Something Data 24 ianuarie 2026 20:58:46
Problema Parcurgere DFS - componente conexe Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");

vector<int> DFS(vector<vector<int>>& lista, vector<int>& viz, int x)
{
    viz[x - 1] = 1;
    for(int vecin : lista[x - 1])
    {
        if(viz[vecin - 1] == 0)
        {
            DFS(lista, viz, vecin);
        }
    }
    return viz;
}

int main()
{
    int n, m, x, y;
    f >> n >> m;
    vector<vector<int>> lista(n);
    for(int i = 0; i < m; i++)
    {
        f >> x >> y;
        lista[x - 1].push_back(y);
        lista[y - 1].push_back(x);
    }

    vector<int> viz(n, 0);
    int comp_conexe = 0;
    for(int i = 0; i < n; i++)
        if(viz[i] == 0)
        {
            comp_conexe++;
            DFS(lista, viz, i + 1);
        }

    g << comp_conexe;

    return 0;
}