Cod sursa(job #3338866)

Utilizator Diaconescu99Mihai Diaconescu Diaconescu99 Data 5 februarie 2026 12:27:13
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
using namespace std;

int n, m, nod;
bool A[101][101], viz[101];
int S[101], vf;

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

void citire()
{
    int x, y;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y;
        A[x][y] = A[y][x] = 1;
    }
}

void DFS(int nod)
{
    vf = 1;
    S[1] = nod;
    viz[nod] = 1;

    while(vf > 0)
    {
        int crt = S[vf];
        bool ok = 0;

        for(int i = 1; i <= n; i++)
            if(A[crt][i] == 1 && viz[i] == 0)
            {
                S[++vf] = i;
                viz[i] = 1;
                ok = 1;
                break;
            }

        if(ok == 0)
            vf--;
    }
}

int main()
{
    citire();

    int comp = 0;
    for(int i = 1; i <= n; i++)
        if(viz[i] == 0)
        {
            comp++;
            DFS(i);
        }

    g << comp;

    f.close();
    g.close();
    return 0;
}