Pagini recente » Cod sursa (job #2754183) | Cod sursa (job #2285892) | Cod sursa (job #1363395) | Cod sursa (job #1774280) | Cod sursa (job #1706754)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector < vector<int> > graph;
vector <bool> visited;
int n,m;
void bfs(int vertex)
{
if(vertex < 0 || vertex>n-1) return;
int element;
queue<int> q;
q.push(vertex);
visited[vertex]=true;
while(!q.empty()) {
element=q.front();
for(int i=0; i<graph[element].size();i++) {
if(!visited[graph[element][i]])
q.push(graph[element][i]);
visited(graph[element][i])=true;
}
q.pop();
}
}
int main()
{
int x,y,nr=0;
cin>>n>>m;
graph.resize(n);
visited.resize(n,false);
for(int i=0; i<m; i++) {
cin>>x>>y;
x--;
y--;
graph[x].push_back(y);
graph[y].push_back(x);
}
for(int i=0; i<visited.size() && i<n;i++)
if(!visited[i]) bfs(i);
}