Cod sursa(job #3235520)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 18 iunie 2024 13:33:13
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 fin("dfs.in");
ofstream fout("dfs.out");

signed main() {
    int n, m;
    fin >> n >> m;
    vector<vector<int>> graph(n + 1);
    vector<bool> visited(n, false);
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    int answer = 0;
    for (int i = 1; i <= n; ++i) {
        stack<int> nodes;
        nodes.push(i);
        if (!visited[i]) {
            visited[i] = true;
            while (!nodes.empty()) {
                int current = nodes.top();
                nodes.pop();
                for (int node : graph[current]) {
                    if (!visited[node]) {
                        nodes.push(node);
                        visited[node] = true;
                    }
                }
            }
            ++answer;
        }
    }
    fout << answer;
    return 0;
}