Pagini recente » Cod sursa (job #1328804) | Cod sursa (job #1230592) | Cod sursa (job #834280) | Cod sursa (job #369019) | Cod sursa (job #3211830)
#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;
fin >> n >> m;
vector<vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int x, y;
fin >> 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++;
}
}
fout << noComponents;
return 0;
}