Cod sursa(job #3293754)

Utilizator AlexAlbisoruAlexandru Albisoru AlexAlbisoru Data 12 aprilie 2025 15:10:22
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;

int v[100005];
int m[100000][100000];
int N, M, X, Y, k=0;
ifstream fin("dfs.in");
ofstream fout("dfs.out");

void DFS(int start)
{   
    bool gasit;
    stack<int>s;
    s.push(start);
    while(!s.empty())
    {
        int nod_curent=s.top();
        gasit=false;
        for(int i=1; i<=N; i++)
        {
            if(v[i]==0 and m[nod_curent][i]==1)
            {
                s.push(i);
                v[i]=1;
                gasit = true;
                break;
            }
        }
        if(!gasit)
        {
            s.pop();
        }
        
    }
}
;

int main()
{
    fin>>N>>M;
    
    for(int i=1; i<=N; i++)
    {
        fin>>X>>Y;
        m[X][Y]=1;
        m[Y][X]=1;
    }
    
    for(int i=1; i<=N; i++)
    {
        if(!v[i])
        {
            k++;
            DFS(i);
        }

    }
    
    fout<<k;
}