0% found this document useful (0 votes)
33 views1 page

438 V2

The document contains C++ code that implements breadth-first search (BFS) to find the connected components in an undirected graph. It takes input of the number of nodes and edges, stores the graph in an adjacency matrix, runs BFS from each unvisited node to label the connected components, and outputs the number of components and the nodes in each component.

Uploaded by

Supy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views1 page

438 V2

The document contains C++ code that implements breadth-first search (BFS) to find the connected components in an undirected graph. It takes input of the number of nodes and edges, stores the graph in an adjacency matrix, runs BFS from each unvisited node to label the connected components, and outputs the number of components and the nodes in each component.

Uploaded by

Supy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <bits/stdc++.

h>
using namespace std;
ifstream f("componenteconexe.in");
ofstream g("componenteconexe.out");
int a[101][101], i, j, n, k = 1, viz[101];
void bf(int x)
{
   int c[101], i, u, v, p;
   c[1] = x;
   viz[x] = k;
   p = 1;
   u = 1;
   while(p <= u)
   {
       v = c[p++];
       for(i = 1; i <= n; i++)
           if(a[v][i] == 1 && viz[i] == 0)
               {
                   c[++u] = i;
                   viz[i] = k;
               }
   }
}
int main()
{
   f >> n;
   while(f >> i >> j)
   {
       a[i][j] = 1;
       a[j][i] = 1;
   }
   bf(1);
   for(i = 1; i <= n; i++)
       if(viz[i] == 0)
           {
               k++;
               bf(i);
           }
   g << k << '\n';
       for(i = 1; i <= k; i++)
           {
               for(j = 1; j <= n; j++)
                   if(viz[j] == i) g << j << " ";
               g << '\n';
           }
   return 0;
}

You might also like