Tutorialspoint
Problem
Solution
Submissions

Number of Connected Components in a Graph

Certification: Advanced Level Accuracy: 100% Submissions: 3 Points: 15

Write a Python function that counts the number of connected components in an undirected graph represented as an adjacency list. A connected component is a subgraph in which any two vertices are connected to each other by paths.

Example 1
  • Input: {0: [1, 2], 1: [0], 2: [0], 3: [4], 4: [3], 5: []}
  • Output: 3
  • Explanation:
    • Step 1: Initialize a visited array to keep track of visited vertices.
    • Step 2: Perform DFS/BFS on each unvisited vertex to explore its connected component.
    • Step 3: Count the number of times we need to start a new DFS/BFS (3 components).
    • Step 4: Return 3 as the number of connected components.
Example 2
  • Input: {0: [1, 2, 3], 1: [0, 2], 2: [0, 1], 3: [0]}
  • Output: 1
  • Explanation:
    • Step 1: Initialize a visited array.
    • Step 2: Start DFS from vertex 0 and mark all reachable vertices as visited.
    • Step 3: All vertices are visited after one DFS traversal, indicating one connected component.
    • Step 4: Return 1 as the number of connected components.
Constraints
  • 1 ≤ number of vertices ≤ 10^5
  • 0 ≤ number of edges ≤ 10^6
  • Graph is represented as an adjacency list
  • Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges
  • Space Complexity: O(V)
GraphRecursionAlgorithmsTCS (Tata Consultancy Services)HCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Depth-First Search (DFS) or Breadth-First Search (BFS) to explore all vertices in a component
  • Keep track of visited vertices to avoid revisiting
  • Increment component count each time you start a new DFS/BFS from an unvisited vertex
  • Use a recursive approach for DFS or a queue for BFS
  • Handle disconnected vertices (vertices with no edges) as separate components

Steps to solve by this approach:

 Step 1: Initialize a visited array to track which nodes have been processed.

 Step 2: Initialize a counter for the number of connected components.
 Step 3: For each unvisited node, increment the counter and perform DFS.
 Step 4: During DFS, mark the current node as visited and recursively visit all its unvisited neighbors.
 Step 5: Return the final count of connected components.

Submitted Code :