Skip to content

Instantly share code, notes, and snippets.

@say4n
Created February 6, 2022 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save say4n/49010838e66906885272aace393e843d to your computer and use it in GitHub Desktop.
Save say4n/49010838e66906885272aace393e843d to your computer and use it in GitHub Desktop.
Finds the number of disconnected components in a graph.
def number_of_disconnected_components(self, adj: List[List[int]]) -> int:
n = len(adj)
visited = set()
components = 0
for i in range(n):
if i not in visited:
visited |= {i}
components += 1
stack = [i]
while stack:
node = stack.pop(-1)
for j in range(n):
if adj[node][j] and j not in visited:
stack.append(j)
visited |= {j}
return components
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment