menu_book Course Curriculum (Data Structures & Algorithms) expand_more
Complexity & Foundations
Arrays & Strings
Linked Lists
Stacks & Queues
Hashing
Trees & Heaps
Graphs
Connected components
Learn Connected components in Data Structures & Algorithms with a focused explanation, a topic-specific example, edge guidance, and a mastery check.
12 min read
•
Advanced
data-structures-algorithms-065.py
python
graph={1:[2],2:[1],3:[4],4:[3],5:[]};seen=set();count=0
for start in graph:
if start in seen:continue
count+=1;stack=[start];seen.add(start)
while stack:
for n in graph[stack.pop()]:
if n not in seen:seen.add(n);stack.append(n)
print(count)
What to watch
Content source & attribution
Original Syntaxis Content · Original Syntaxis Content