Skip to content

Commit

Permalink
solve : number of conntected components in an undirected graph
Browse files Browse the repository at this point in the history
  • Loading branch information
SamTheKorean committed Jul 5, 2024
1 parent 8cc29ac commit bdab952
Showing 1 changed file with 23 additions and 0 deletions.
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

0 comments on commit bdab952

Please sign in to comment.