Cod sursa(job #2628902)

Utilizator robeert.77Chirica Robert robeert.77 Data 17 iunie 2020 22:37:42
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>
using namespace std;

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

vector <int> graph[100001];
int n, m;

void read() {
    fin >> n >> m;
    int x, y;
    for (int i = 0; i < m; i++) {
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
}

void dfs(int node, bool vizited[]) {
    vizited[node] = true;
    for (vector <int> :: iterator it = graph[node].begin(); it != graph[node].end(); it++)
        if (!vizited[*it])
            dfs(*it, vizited);
}

int main() {
    read();

    bool vizited[n + 1] = {0};
    int nrComponent = 0;
    for (int i = 1; i <= n; i++)
        if (!vizited[i]) {
            dfs(i, vizited);
            nrComponent++;
        }

    fout << nrComponent;

    return 0;
}