Cod sursa(job #3336530)

Utilizator SomethingAndrei Marian Something Data 24 ianuarie 2026 21:09:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

// void 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);
// }

void DFS(vector<vector<int>>& lista, vector<int>& viz, int x)
{
    viz[x - 1] = 1;
    stack<int> stiva;
    stiva.push(x);
    while(!stiva.empty())
    {
        int nod = stiva.top();
        stiva.pop();
        for(int vecin : lista[nod - 1])
        {
            if(viz[vecin - 1] == 0)
            {
                viz[vecin - 1] = 1;
                stiva.push(vecin);
            }
        }
    }
}

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;
}