Pagini recente » Cod sursa (job #2417508) | Cod sursa (job #3032257) | Cod sursa (job #690547) | Cod sursa (job #484646) | Cod sursa (job #1458627)
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;
void dfs (int x, int n, vector<bool>& vis, list<int> adj[])
{
list<int>::iterator it;
vis[x] = true;
for (it = adj[x].begin(); it != adj[x].end(); ++it)
//for (int i = 0; i < adj[x].size(); ++i)
{
if (!vis[*it])
{
dfs (*it, n, vis, adj);
}
}
}
int main()
{
int nrConexe = 0;
int m, n, i, x, y;
//list<int> adj;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
fin >> n;
fin >> m;
list<int> adj[n + 1];
vector<bool> vis(n + 1);
for (i = 0 ;i<=n-1;i++)
vis[i]=false;
for (i = 0 ; i <= m-1; i++)
{
fin>>x;
fin>>y;
adj[x].push_back(y);
adj[y].push_back(x);
}
for (i = 0; i <= n-1 ;i++)
{
//cout<<i<<" ";
//for (int j=0;j<=n-1;j++)
// cout<<vis[j]<<" ";
//cout<<endl;
if (!vis[i + 1])
{
++nrConexe;
dfs(i + 1, n, vis, adj);
}
}
fout<<nrConexe;
fin.close();
fout.close();
return 0;
}