Cod sursa(job #2751259)

Utilizator MindralexMindrila Alex Mindralex Data 14 mai 2021 17:24:28
Problema Parcurgere DFS - componente conexe Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.67 kb
#include <iostream>
#include <fstream>

using namespace std;

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

bool mat[1001][1001], f[1001];
int n;

void dfs (int x)
{
    f[x] = 1;
    for (int i = 1; i <= n; i++)
        if (mat[x][i] && f[i] == 0)
            dfs(i);
}

int main()
{
    int m;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        mat[x][y] = mat[y][x] = 1;
    }
    int componente = 0;
    for (int i = 1; i <= n; i++)
    {
        if (f[i] == 0)
        {
            componente++;
            dfs(i);
        }

    }
    fout << componente;
    return 0;
}