Cod sursa(job #3123582)

Utilizator mihaisoare349Soare Mihai-Alexandru mihaisoare349 Data 24 aprilie 2023 20:01:13
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

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

int main() {
    int n,m;
    std::cin >> n >> m;
    std::vector<std::vector<int>> adj(6);
    while(m--) {
        int a, b;
        std::cin >> a >> b;
        a--, b--;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    std::vector<bool> visited(n, false);
    int cnt{};
    for(int i = 0; i<n; i++) {
        if(!visited[i]) {
            cnt++;
            std::stack<int> q;
            q.push(i);
            visited[i] = true;
            while(!q.empty()) {
                int node = q.top();
                q.pop();
                for(auto next : adj[node]) {
                    if(!visited[next]) {
                        visited[next] = true;
                        q.push(next);
                    }
                }
            }
        }
    }

    std::cout << cnt << '\n';
    return 0;
}