File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments