Skip to content

Commit bdab952

Browse files
committed
solve : number of conntected components in an undirected graph
1 parent 8cc29ac commit bdab952

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# O(n+e) where n is number of nodes and e is the number of edges.
2+
# O(n+e) where n is number of nodes and e is the number of edges.
3+
class Solution:
4+
def countComponents(self, numNodes: int, connections: List[List[int]]) -> int:
5+
adjacencyList = [[] for _ in range(numNodes)]
6+
for src, dst in connections:
7+
adjacencyList[src].append(dst)
8+
adjacencyList[dst].append(src)
9+
10+
visitedNodes = set()
11+
12+
def depthFirstSearch(node):
13+
visitedNodes.add(node)
14+
for neighbor in adjacencyList[node]:
15+
if neighbor not in visitedNodes:
16+
depthFirstSearch(neighbor)
17+
18+
componentCount = 0
19+
for node in range(numNodes):
20+
if node not in visitedNodes:
21+
componentCount += 1
22+
depthFirstSearch(node)
23+
return componentCount

0 commit comments

Comments
 (0)