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

Image of Timescale

📊 Benchmarking Databases for Real-Time Analytics Applications

Benchmarking Timescale, Clickhouse, Postgres, MySQL, MongoDB, and DuckDB for real-time analytics. Introducing RTABench 🚀

Read full post →

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If you found this post useful, consider leaving a ❤️ or a nice comment!

Got it