Mai intai trebuie sa te autentifici.
Cod sursa(job #3243670)
Utilizator | Data | 20 septembrie 2024 11:08:46 | |
---|---|---|---|
Problema | Parcurgere DFS - componente conexe | Scor | 100 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 0.77 kb |
#include <fstream>
#include <vector>
using namespace std;
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;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
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 countt = 0;
vector<bool> visited(n + 1);
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
countt++;
dfs(graph, visited, i);
}
}
fout << countt << "\n";
return 0;
}