Cod sursa(job #1612666)

Utilizator pulseOvidiu Giorgi pulse Data 24 februarie 2016 23:12:16
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

int N, M;
vector < vector<int> > graph;
vector <bool> visited;

void DFS(int vertex) {
    if (vertex < 0 || vertex > N - 1) {
        return;
    }

    stack <int> S;
    int node, i;
    bool found;

    S.push(vertex);
    visited[vertex] = true;
    while (!S.empty()) {
        node = S.top();
        found = false;
        for (i = 0; i < graph[node].size() && !found; ++i) {
            if (!visited[graph[node][i]]) {
                found = true;
            }
        }
        if (found) {
            i--;
            S.push(graph[node][i]);
            visited[graph[node][i]] = true;
        }
        else {
            S.pop();
        }
    }
}

int main() {
    fin >> N >> M;
    graph.resize(N);
    visited.resize(N, false);
    for (int i = 0; i < M; ++i) {
        int x, y;
        fin >> x >> y;
        x--;
        y--;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    int ans = 0;
    for (int i = 0; i < visited.size() && i < N; ++i) {
        if (!visited[i]) {
            ++ans;
            DFS(i);
        }
    }

    fout << ans;

    return 0;
}