Number of Connected Components Using BFS in graph

Here's the code that i have written to find the number of connected components in graph using BFS in python

# Let's consider 2D dimension graph as 'M' and visited array as 'visited' of length number of total vertices

		queue=[]
        self.count=0
        visited=[0]*len(M)
        def countComponent(current):
            queue.append(current)
            while len(queue)!=0:
                current = queue.pop(0)
                if not visited[current]:
                    visited[current]=1
                    for i in range(len(M)):
                        if M[current][i]==1 and visited[i]==0:
                            queue.append(i)
            self.count+=1
        for i in range(len(M)):
            if visited[i]==0:
                countComponent(i)
        return self.count
Comments (0)