Pagini recente » Cod sursa (job #1384142) | Cod sursa (job #1813036) | Cod sursa (job #867892) | Cod sursa (job #3256068) | Cod sursa (job #3243760)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
void dfs(vector<vector<int>> &graph, vector<bool> &visited,int node)
{
visited[node]=true;
for(int neighbor:graph[node])
{
if(!visited[neighbor])
{
dfs(graph,visited,neighbor);
}
}
}
int main()
{
int n,m;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
fin >> n >> m;
vector<vector<int>> graph(n+1,vector<int> ());
vector<bool> visited(n+1,false);
for(int i=1;i<=m;i++)
{
int x,y;
fin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
int cnt=0;
for(int i=1;i<=n;i++)
{
if(!visited[i])
{
cnt++;
dfs(graph,visited,i);
}
}
fout << cnt;
return 0;
}