Cod sursa(job #3271381)

Utilizator andu9andu nita andu9 Data 25 ianuarie 2025 21:10:06
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <bitset>
#include <vector>
#include <queue>

const int nMax = 1e5;

void DFS(std::vector<std::vector<int>>& graph, std::bitset<nMax>& vis, int currNode) {
    vis[currNode] = true;
    for (int& next : graph[currNode]) {
        if (vis[next] == false) {
            DFS(graph, vis, next);
        }
    }
}

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

    int n, m; fin >> n >> m;
    std::vector<std::vector<int>> graph(n, std::vector<int>());
    for (int i = 0; i < m; i += 1) {
        int u, v; fin >> u >> v; u -= 1, v -= 1;
        graph[u].emplace_back(v), graph[v].emplace_back(u);
    }

    int connectedComponents = 0;
    std::bitset<nMax> vis;
    for (int i = 0; i < n; i += 1) {
        if (vis[i] == false) {
            DFS(graph, vis, i);
            connectedComponents += 1;
        }
    }

    fout << connectedComponents;

    graph.clear();
    fin.close(), fout.close();
    return 0;
}