Pagini recente » Cod sursa (job #2217590) | Cod sursa (job #2753813) | Cod sursa (job #938964) | Cod sursa (job #2818350) | Cod sursa (job #3211826)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
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;
cin >> n >> m;
vector<vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
vector<bool> visited(n + 1, false);
int noComponents = 0;
for (int i = 1; i <= n; ++i) {
if (!visited[i]) {
dfs(graph, visited, i);
noComponents++;
}
}
cout << noComponents;
return 0;
}