Created
February 6, 2022 17:58
-
-
Save say4n/49010838e66906885272aace393e843d to your computer and use it in GitHub Desktop.
Finds the number of disconnected components in a graph.
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
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