Pagini recente » Cod sursa (job #2148456) | Cod sursa (job #2285009) | Cod sursa (job #338872) | Cod sursa (job #1366594) | Cod sursa (job #3244128)
#include <vector>
#include <fstream>
using namespace std;
void dfs(vector<vector<int>> &graph, vector<bool> &isVisited, int node) {
isVisited[node] = 1;
for(int neighbour : graph[node]) {
if(!isVisited[neighbour]) {
dfs(graph, isVisited, neighbour);
}
}
}
int main() {
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int n,m;
fin >> n >> m;
vector<vector<int>> graph(n+1, vector<int>());
for(int i=1; i<=m; i++) {
int x,y;
fin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
int sol = 0;
vector<bool> isVisited(n+1);
for(int i=1; i<=n; i++) {
if(!isVisited[i]) {
sol++;
dfs(graph, isVisited, i);
}
}
fout << sol;
return 0;
}