Pagini recente » Cod sursa (job #3159340) | Cod sursa (job #2654090) | Cod sursa (job #94689) | Cod sursa (job #2400789) | Cod sursa (job #3270960)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
void dfs(const vector<vector<int>>& graph, vector<bool>& visited, int start)
{
queue<int> q;
visited[start] = true;
q.push(start);
while(!q.empty())
{
int node = q.front();
q.pop();
for(int neigh: graph[node])
{
if(!visited[neigh]) {
q.push(neigh);
visited[neigh] = true;
}
}
}
}
int main()
{
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int n, m, s;
fin >> n >> m;
vector<vector<int>> graph(n + 1);
for(int i = 0; i < m; i++)
{
int a, b;
fin >> a >> b;
graph[a].push_back(b);
}
vector<bool> visited(n + 1);
int conexe = 0;
for(int i = 1; i <= n; i++)
{
if(!visited[i])
{
dfs(graph, visited, i);
++conexe;
}
}
fout << conexe;
return 0;
}