Skip to content

Instantly share code, notes, and snippets.

@kushaagr
Last active March 23, 2025 16:13
Show Gist options
  • Save kushaagr/a8c5149aee9b950ae2f2b1489d92036e to your computer and use it in GitHub Desktop.
Save kushaagr/a8c5149aee9b950ae2f2b1489d92036e to your computer and use it in GitHub Desktop.
[Connected components] Count connected components using DFS
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