Pagini recente » Cod sursa (job #1138519) | Cod sursa (job #1433072) | Cod sursa (job #1795872) | Cod sursa (job #2862253) | Cod sursa (job #3247576)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}
int main() {
ifstream fin("dfs.in");
ofstream fout("dfs.out");
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 components = 0;
for (int i = 1; i <= N; i++) {
if (!visited[i]) {
dfs(i, graph, visited);
components++;
}
}
fout << components << endl;
fin.close();
fout.close();
return 0;
}