Pagini recente » Cod sursa (job #2038668) | Cod sursa (job #1924135) | Cod sursa (job #680896) | Cod sursa (job #3189083) | Cod sursa (job #3269512)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
// vector <int> - un tip de date
vector <int> graph[100005]; // graph[i] - vector <int>
// int graph[100005]; // graph[i] - int
// graph[1] - este un vector <int> si va contine toti vecinii lui 1 - initia este gol
int visited[100005];
void dfs(int node) {
visited[node] = 1; // vizitam nodul curent pentru a nu intra in el din nou
// for (int i = 0; i < graph[node].size(); ++i) x = graph[node][i];
for (auto x : graph[node]) {
if (visited[x]) continue;
dfs(x);
}
}
int main()
{
int n, m;
fin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y;
fin >> x >> y;
graph[x].push_back(y); // pushez nodul y in lista de vecini ai lui x
graph[y].push_back(x); // pushez nodul x in lista de vecini ai lui y pentru ca graful este neorientat
}
int counter = 0;
for (int i = 1; i <= n; ++i) {
if (visited[i]) continue;
dfs(i);
++counter;
}
fout << counter;
return 0;
}