Cod sursa(job #1614271)

Utilizator jeronimoPopovici Daniel jeronimo Data 25 februarie 2016 21:22:29
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include<iostream>
#include<fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream f("graf.in");
ofstream g("graf.out");
int n;
vector<vector<int> > graf;
vector<bool> visited;
void dfs(int x,int n)
{
    int i;
    if(x<0 || x>n-1)
        return;
    stack<int> s;
    int element;
    bool found;
    s.push(x);
    visited[x]=true;
    while(!s.empty())
    {
        element=s.top();
        found=false;
        for(i=0; i<graf[element].size() && !found; i++)
        {
            if(!visited[graf[element][i]])
                found=true;
        }
        if(found)
        {
            i--;
            s.push(graf[element][i]);
            visited[graf[element][i]]=true;
        }
        else
        {
            s.pop();
        }
    }

}
int main()
{
    int i,j,x,y,n,m,c=0;
    f>>n>>m;
    graf.resize(n);
    visited.resize(n,false);
    for(i=0;i<m;i++)
    {
        f>>x>>y;
        x--;
        y--;
        graf[x].push_back(y);
        graf[y].push_back(x);

    }
    for(i=0; i<visited.size() && i<n; i++)
    {
        if(!visited[i])
        {
            dfs(i,n);
            c++;
        }
    }
    g<<c;
    return 0;
    f.close();
}