Cod sursa(job #3352246)

Utilizator alexcomanAlex Coman alexcoman Data 25 aprilie 2026 14:56:31
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.61 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream cin("dfs.in");
ofstream cout("dfs.out");
#define Maxx 100005

vector<int> v[Maxx];
bool viz[Maxx];
void DFS(int node) {
  viz[node] = true;
  for (auto vecin : v[node]) {
    if (!viz[vecin])
      DFS(vecin);
  }
}

int main() {
  int N, M, componente = 0, x, y;
  cin >> N >> M;
  for (int i = 0; i < M; ++i) {
    cin >> x >> y;
    v[x].push_back(y);
    v[y].push_back(x);
  }
  for (int i = 1; i <= N; ++i) {
    if (!viz[i]){
      DFS(i);
    componente++;
    }
  }
  cout << componente;
  return 0;
}

// https://www.infoarena.ro/problema/dfs