Cod sursa(job #3233204)

Utilizator MirceaDonciuLicentaLicenta Mircea Donciu MirceaDonciuLicenta Data 2 iunie 2024 19:26:21
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

void dfs(int node, const vector<vector<int>>& adj, vector<bool>& visited) {
    visited[node] = true;
    for (int neighbor : adj[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor, adj, visited);
        }
    }
}

int main() {
    ifstream infile("dfs.in");
    ofstream outfile("dfs.out");

    if (!infile || !outfile) {
        cerr << "Error opening file" << endl;
        return 1;
    }

    int N, M;
    infile >> N >> M;

    vector<vector<int>> adj(N + 1);

    for (int i = 0; i < M; ++i) {
        int x, y;
        infile >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);  // because the graph is undirected
    }

    vector<bool> visited(N + 1, false);
    int components = 0;

    for (int i = 1; i <= N; ++i) {
        if (!visited[i]) {
            dfs(i, adj, visited);
            components++;
        }
    }

    outfile << components << endl;

    infile.close();
    outfile.close();

    return 0;
}