Skip to content

Instantly share code, notes, and snippets.

@nvlong198
Created April 13, 2018 11:27
Show Gist options
  • Save nvlong198/cc7ad697c0767b9626c643cc9981509e to your computer and use it in GitHub Desktop.
Save nvlong198/cc7ad697c0767b9626c643cc9981509e to your computer and use it in GitHub Desktop.
Find Clusters using BFS
#include<iostream>
#include <list>
using namespace std;
int** adj; // array's adjacent vertices
bool* visited; // visited defalt false
int highestVertex;
int counter = 0;
void BFS(int v){ // breadth first search traversal
if(!visited[v]){
list <int> gqueue;
gqueue.push_back(v);
visited[v] = true;
while(!gqueue.empty()){
v = gqueue.front();
gqueue.pop_front();
for(int i = 1; i <= highestVertex; i++){
if( adj[v][i] == 1 && visited[i] == false){
visited[i] = true;
gqueue.push_back(i);
}
}
}
counter++;
}
}
int main(){
int n, m;
cin >> highestVertex; // cin numbers verties
adj = new int*[highestVertex];
visited = new bool[highestVertex];
for(int i = 0; i < highestVertex; ++i)
adj[i] = new int[highestVertex]; // declare
for(int i = 0; i < highestVertex; i++){
for(int j = 0; j < highestVertex; j++){
cin >> adj[i][j];
}
}
for(int i = 0; i < highestVertex; i++){
if(!visited[i]){
BFS(i);
}
}
cout << counter;
return 0;
}
/*
4
1 1 0 0
1 1 1 0
0 1 1 0
0 0 0 1 => 2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment