Pagini recente » Cod sursa (job #1869622) | Cod sursa (job #873148) | Cod sursa (job #3236218) | Cod sursa (job #173198) | Cod sursa (job #3123745)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int main(){
int N, M;
fin >> N >> M;
vector<vector<int> > adj(N + 1);
for (int i = 0; i < M; i++){
int x, y;
fin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
// Find the number of connected components in the graph
int nr = 0;
vector<bool> visited(N + 1, false);
queue<int> q;
for (int i = 1; i <= N; i++){
if (!visited[i]){
nr++;
q.push(i);
visited[i] = true;
while (!q.empty()){
int node = q.front();
q.pop();
for (int neighbour : adj[node]){
if (!visited[neighbour]){
q.push(neighbour);
visited[neighbour] = true;
}
}
}
}
}
fout << nr;
}