Skip to content

Commit 4ecdba1

Browse files
author
Hardik dadhich
committed
Find Total Number of Connected Component in Graph
1 parent ac1718e commit 4ecdba1

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#count connected no of component using DFS
2+
'''
3+
In graph theory, a component, sometimes called a connected component,
4+
of an undirected graph is a subgraph in which any
5+
two vertices are connected to each other by paths.
6+
7+
Example:
8+
9+
10+
1 3------------7
11+
|
12+
|
13+
2--------4
14+
| |
15+
| | output = 2
16+
6--------5
17+
18+
'''
19+
20+
# Code is Here
21+
22+
def dfs(source,visited):
23+
''' Function that performs DFS '''
24+
25+
visited[source] = True
26+
for child in l[source]:
27+
if not visited[child]:
28+
dfs(child,visited)
29+
30+
def count_components(l,size):
31+
'''
32+
Function that counts the Connected components on bases of DFS.
33+
return type : int
34+
'''
35+
36+
count = 0
37+
visited = [False]*(size+1)
38+
for i in range(1,size+1):
39+
if not visited[i]:
40+
dfs(i,visited)
41+
count+=1
42+
return count
43+
44+
45+
# Driver code
46+
if __name__ == '__main__':
47+
n,m = map(int, input("Enter the Number of Nodes and Edges \n").split(' '))
48+
l = [[] for _ in range(n+1)]
49+
for i in range(m):
50+
print("Enter the edge's Nodes in form of a b\n")
51+
a,b = map(int,input().split(' '))
52+
l[a].append(b)
53+
l[b].append(a)
54+
print("Total number of Connected Components are : ", count_components(l,n))

0 commit comments

Comments
 (0)