Cod sursa(job #2784756)

Utilizator Tache_RoxanaTache Roxana Tache_Roxana Data 17 octombrie 2021 12:14:38
Problema Parcurgere DFS - componente conexe Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <deque>
#include <fstream>
using namespace std;

int n, m, a[1000][1000], nrComponente = 0, vizitate[1000];
deque<int> negasite;

void dfs(int x) {
    //cout << x << " ";
    deque<int>::iterator pozitie;
    for(int i = 1; i <= n; i++)
        if(a[x][i] == 1 && vizitate[i] == 0) {
            for(auto j = negasite.begin(); j != negasite.end(); j++)
                if(*j == i)
                    pozitie = j;
            negasite.erase(pozitie);
            dfs(i);
        }
}

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

    in >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y;
        in >> x >> y;
        a[x][y] = a[y][x] = 1;
    }
    for(int i = 1; i <= n; i++)
        negasite.push_back(i);

    while(negasite.size() != 0) {
        int actual = negasite.front();
        negasite.pop_front();
        for(int i = 1; i <= n; i++)
            vizitate[i] = 0;
        vizitate[actual] = 1;
        nrComponente++;
        dfs(actual);
    }
    out << nrComponente;
    return 0;
}