Cod sursa(job #2597062)

Utilizator RobertLearnsCDragomir Robert. RobertLearnsC Data 11 aprilie 2020 09:39:55
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, s, visited[100005], x,  y;
vector <int> graph[100005];

void dfs(int i) {
    queue <int> depthSearch;
    depthSearch.push(i);

    visited[i] = 1;
    while(depthSearch.size()) {
        int adj = depthSearch.front();
        depthSearch.pop();
        for(int j = 0; j < graph[adj].size(); j++) {
            int curr = graph[adj][j];
            if(visited[curr] == 0) {
                visited[curr] = 1;
                depthSearch.push(curr);
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i++) {
        in >> x >> y;
        graph[y].push_back(x);
        graph[x].push_back(y);
    }

    int components = 0;
    for(int i = 1; i <= n; i++) {
        if(visited[i] == 0) {
            dfs(i);
            ++components;
        }
    }
    out << components;
    return 0;
}