Cod sursa(job #3330700)

Utilizator Bogdan222Bogdan Caraeane Bogdan222 Data 21 decembrie 2025 13:13:21
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
#include <fstream>

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

const int NMAX = 1e5 + 5;
const char nl = '\n';



vector<int> g[NMAX];
int v[NMAX];

void dfs (int source) {
    stack<int> st;
    st.push(source);
    while (!st.empty()) {
        int curr_node = st.top();
        st.pop();
        for (auto neigh: g[curr_node]) {
            if (v[neigh] == 1) {
                continue;
            }
            else {
                st.push(neigh);
                v[neigh] = 1;
            }
        }
    }
}

int main () {
    int n, m, conexe = 0;
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    for (int i = 1; i <= n; i++) {
        if (v[i] == 1) {
            continue;
        }
        else {
            dfs(i);
            conexe++;
        }
    }
    fout << conexe;
}