13(May) Number of Good Components

13. Number of Good Components

The problem can be found at the following link: Question Link

Problem Description

Given an undirected graph with (v) vertices (numbered from 1 to (v)) and (e) edges, find the number of good components in the graph. A component of the graph is good if and only if the component is fully connected.

Example:

Input:

Image

Output:

Explanation: There is only one component in the graph, and in this component, there is an edge between any two vertices.

My Approach

  1. Initialization:

    • Initialize a variable ans to store the number of good components, initially set to 0.

    • Create a vector visited to mark visited vertices, initialized with 0.

    • Create an adjacency list adj to represent the graph.

  2. Building Graph:

    • Populate the adjacency list adj using the provided edges.

  3. DFS Traversal:

    • Perform Depth-First Search (DFS) traversal starting from each unvisited vertex.

    • While traversing, count the number of vertices and edges in the connected component.

    • Check if the number of edges in the component is equal to (\frac{{\text{vertices} \times (\text{vertices} - 1)}}{2}), indicating a fully connected component.

    • If yes, increment ans by 1.

  4. Return:

    • Return ans, the total number of good components.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(v + e), as we visit each vertex and edge once during DFS traversal.

  • Expected Auxiliary Space Complexity: O(depth of the graph), as we use a stack for DFS traversal and additional space proportional to the depth of the graph.

Code (C++)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated