Cod sursa(job #1108330)

Utilizator A63N7pTudor Nazarie A63N7p Data 15 februarie 2014 16:30:52
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
#include <vector>
#define NMAX 100005

using namespace std;

int n,m;
vector<int> graph[NMAX];
int visited[NMAX];

void DFS(int x);

int main()
{
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    scanf("%d%d", &n, &m);

    for (int i = 0; i < m; ++i)
    {
        int x,y;
        scanf("%d%d",&x,&y);

        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    int count=0;

    for (int i = 1; i <= n; ++i)
    {
        if (!visited[i])
        {
            DFS(i);
            count+=1;
        }
    }

    printf("%d", count);

    return 0;
}

void DFS(int x)
{
    visited[x]=1;
    for (unsigned int i = 0; i < graph[x].size(); ++i)
        if (!visited[graph[x][i]])
            DFS(graph[x][i]);
}