Cod sursa(job #2973950)

Utilizator SennyUrsu Arsenie Senny Data 2 februarie 2023 20:41:09
Problema Parcurgere DFS - componente conexe Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include<bits/stdc++.h>
using namespace std;
int N, M;
const int N_LIM = 10005;
vector<int> muchii[N_LIM];
bool vizitat[N_LIM];
int insule = 0;

void DFS(int nod){
    vizitat[nod] = true;
    for (unsigned int i = 0; i < muchii[nod].size(); i++){
        int vecin = muchii[nod][i];
        if (!vizitat[vecin]) DFS(vecin);
    }
}

void citire()
{
    cin >> N >> M;
    for (int i = 1; i <= M; i++) {
        int x, y;
        cin >> x >> y;
        muchii[x].push_back(y);
        muchii[y].push_back(x);
    }
    for (int i = 1; i <= N; i++){
        if (!vizitat[i])
        {
            insule+=1;
            DFS(i);
        }
    }
}
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    citire();
    cout << insule << endl;
    return 0;
}