Cod sursa(job #2670158)

Utilizator As932Stanciu Andreea As932 Data 9 noiembrie 2020 10:42:27
Problema Parcurgere DFS - componente conexe Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.64 kb
#include <fstream>

using namespace std;

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

const int nMax = 1e3 + 5;

int n, m, ans;
bool viz[nMax];
bool a[nMax][nMax];

void read(){
    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        int x, y;

        fin >> x >> y;

        a[x][y] = a[y][x] = 1;
    }
}

void dfs(int nod){
    viz[nod] = 1;

    for(int i = 1; i <= n; i++)
        if(a[nod][i] && !viz[i])
            dfs(i);
}

int main()
{
    read();


    for(int i = 1; i <= n; i++)
        if(!viz[i]){
            ans++;
            dfs(i);
        }

    fout << ans;

    return 0;
}