Last active
March 23, 2025 16:13
-
-
Save kushaagr/a8c5149aee9b950ae2f2b1489d92036e to your computer and use it in GitHub Desktop.
[Connected components] Count connected components using DFS
This file contains hidden or 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 recursivelyMark(nodeID, nodes): | |
(connections, visited) = nodes[nodeID] | |
if visited: | |
return | |
nodes[nodeID][1] = True | |
for connectedNodeID in connections: | |
recursivelyMark(connectedNodeID, nodes) | |
def main(): | |
nodes = [[[1], False], [[0], False], [[3], False], [[2], False], [[], False], [[], False]] | |
# nodes = [ [[],False] for _ in nodes_list ] | |
componentsCount = 0 | |
for (nodeID, (connections, visited)) in enumerate(nodes): | |
if visited == False: | |
componentsCount += 1 | |
recursivelyMark(nodeID, nodes) | |
print(componentsCount) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment