Cod sursa(job #1399469)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 24 martie 2015 19:14:39
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>

using namespace std;

#define MAX_VERT 100001

bool u[MAX_VERT];
vector < int > adjList[MAX_VERT];

void DFS(int node) {
    int nextNode, i;
    for(i = 0; i < adjList[node].size(); i++) {
        nextNode = adjList[node][i];
        if(!u[nextNode]) {
            u[nextNode] = 1;
            DFS(nextNode);
        }
    }
}

int main() {
    ifstream in("dfs.in");
    ofstream out("dfs.out");
    
    int n, m, x, y, i, cntConex = 0;
    
    in >> n >> m;
    for(i = 1; i <= m; i++) {
        in >> x >> y;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
    }
    
    for(i = 1; i <= n; i++) 
        if(!u[i]) {
            cntConex++;
            DFS(i);
        }
        
    out << cntConex;
    
    return 0;
}