DEV Community

Bernice Waweru
Bernice Waweru

Posted on

3 2

Number of Connected Components in an Undirected Graph

Instructions

Count the number of connected components in an undirected graph.

Approach

We initialize count and iterate through every node in the graph traversing through its neighbors as far as possible. We increment count by 1 when there are no more nodes in the connected component.
We also need to keep track of the visited nodes to avoid a loop and duplicate look up.

Implementation

def countComponents(graph):
    count = 0
    visited = set()
    for node in graph:
        if traverse(graph,node,visited) == True:
            count+=1
    return count
def traverse(graph,current,visited):
    if current in visited:
        return False
    visited.add(current)
    for neighbor in graph[current]:
        traverse(graph, neighbor,visited)
    return True     
graph = {
    'a': ['c', 'b'],
    'b': ['d'],
    'c': ['e'],
    'd': ['f'],
    'e': [],
    'f': [],
    'g':[]
}
print(countComponents(graph))
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay