-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solve : number of conntected components in an undirected graph
- Loading branch information
1 parent
8cc29ac
commit bdab952
Showing
1 changed file
with
23 additions
and
0 deletions.
There are no files selected for viewing
23 changes: 23 additions & 0 deletions
23
number-of-connected-components-in-an-undirected-graph/samthekorean.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# O(n+e) where n is number of nodes and e is the number of edges. | ||
# O(n+e) where n is number of nodes and e is the number of edges. | ||
class Solution: | ||
def countComponents(self, numNodes: int, connections: List[List[int]]) -> int: | ||
adjacencyList = [[] for _ in range(numNodes)] | ||
for src, dst in connections: | ||
adjacencyList[src].append(dst) | ||
adjacencyList[dst].append(src) | ||
|
||
visitedNodes = set() | ||
|
||
def depthFirstSearch(node): | ||
visitedNodes.add(node) | ||
for neighbor in adjacencyList[node]: | ||
if neighbor not in visitedNodes: | ||
depthFirstSearch(neighbor) | ||
|
||
componentCount = 0 | ||
for node in range(numNodes): | ||
if node not in visitedNodes: | ||
componentCount += 1 | ||
depthFirstSearch(node) | ||
return componentCount |