Open In App

Strongly Connected Components

Last Updated : 05 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Strongly Connected Components (SCCs) are a fundamental concept in graph theory and algorithms. In a directed graph, a Strongly Connected Component is a subset of vertices where every vertex in the subset is reachable from every other vertex in the same subset by traversing the directed edges. Finding the SCCs of a graph can provide important insights into the structure and connectivity of the graph, with applications in various fields such as social network analysis, web crawling, and network routing. This tutorial will explore the definition, properties, and efficient algorithms for identifying Strongly Connected Components in graph data structures

What is Strongly Connected Components (SCCs)?

A strongly connected component of a directed graph is a maximal subgraph where every pair of vertices is mutually reachable. This means that for any two nodes A and B in this subgraph, there is a path from A to B and a path from B to A.

For example: The below graph has two strongly connected components {1,2,3,4} and {5,6,7} since there is path from each vertex to every other vertex in the same strongly connected component. 

scc_fianldrawio

Strongly Connected Component

Why Strongly Connected Components (SCCs) are Important?

Understanding SCCs is crucial for various applications such as:

  • Network Analysis: Identifying clusters of tightly interconnected nodes.
  • Optimizing Web Crawlers: Determining parts of the web graph that are closely linked.
  • Dependency Resolution: In software, understanding which modules are interdependent.

Difference Between Connected and Strongly Connected Components (SCCs)

Connectivity in a undirected graph refers to whether two vertices are reachable from each other or not. Two vertices are said to be connected if there is path between them. Meanwhile Strongly Connected is applicable only to directed graphs. A subgraph of a directed graph is considered to be an Strongly Connected Components (SCC) if and only if for every pair of vertices A and B, there exists a path from A to B and a path from B to A. Let’s see why the standard dfs method to find connnected components in a graph cannot be used to determine strongly connected components.

Consider the following graph:

scc_fianldrawio

Now, let’s start a dfs call from vertex 1 to visit other vertices.

dfs_finaldrawio

Why conventional DFS method cannot be used to find the strongly connected components?

All the vertices can be reached from vertex 1. But vertices 1 and 5,6,7 can not be in the same strongly connected component because there is no directed path from vertex 5,6 or 7 to vertex 1. The graph has two strongly connected components {1,2,3,4} and {5,6,7}. So the conventional dfs method cannot be used to find the strongly connected components.

Connecting Two Strongly Connected Component by a Unidirectional Edge

Two different connected components becomes a single component if a edge is added between a vertex from one component to a vertex of other component. But this is not the case in strongly connected components. Two strongly connected components doesn’t become a single strongly connected component if there is only a unidirectional edge from one SCC to other SCC.

unidrawio-(2)

Brute Force Approach for Finding Strongly Connected Components

The simple method will be for each vertex i (which is not a part of any strongly component) find the vertices which will be the part of strongly connected component containing vertex i. Two vertex i and j will be in the same strongly connected component if they there is a directed path from vertex i to vertex j and vice-versa.

Let’s understand the approach with the help of following example:

exampledrawio

  • Starting with vertex 1. There is path from vertex 1 to vertex 2 and vice-versa. Similarly there is a path from vertex 1 to vertex 3 and vice versa. So, vertex 2 and 3 will be in the same Strongly Connected Component as vertex 1. Although there is directed path form vertex 1 to vertex 4 and vertex 5. But there is no directed path from vertex 4,5 to vertex 1 so vertex 4 and 5 won’t be in the same Strongly Connected Component as vertex 1. Thus Vertex 1,2 and 3 forms a Strongly Connected Component.
  • For Vertex 2 and 3, there Strongly Connected Component has already been determined.
  • For Vertex 4, there is a path from vertex 4 to vertex 5 but there is no path from vertex 5 to vertex 4. So vertex 4 and 5 won’t be in the Same Strongly Connected Component. So both Vertex 4 and Vertex 5 will be part of Single Strongly Connected Component.
  • Hence there will be 3 Strongly Connected Component {1,2,3}, {4} and {5}.

Below is the implementation of above approach:

C++
#include <bits/stdc++.h>
using namespace std;

class GFG {
public:
    // dfs Function to reach destination
    bool dfs(int curr, int des, vector<vector<int> >& adj,
             vector<int>& vis)
    {

        // If curr node is destination return true
        if (curr == des) {
            return true;
        }
        vis[curr] = 1;
        for (auto x : adj[curr]) {
            if (!vis[x]) {
                if (dfs(x, des, adj, vis)) {
                    return true;
                }
            }
        }
        return false;
    }

    // To tell whether there is path from source to
    // destination
    bool isPath(int src, int des, vector<vector<int> >& adj)
    {
        vector<int> vis(adj.size() + 1, 0);
        return dfs(src, des, adj, vis);
    }

    // Function to return all the strongly connected
    // component of a graph.
    vector<vector<int> > findSCC(int n,
                                 vector<vector<int> >& a)
    {
        // Stores all the strongly connected components.
        vector<vector<int> > ans;

        // Stores whether a vertex is a part of any Strongly
        // Connected Component
        vector<int> is_scc(n + 1, 0);

        vector<vector<int> > adj(n + 1);

        for (int i = 0; i < a.size(); i++) {
            adj[a[i][0]].push_back(a[i][1]);
        }

        // Traversing all the vertices
        for (int i = 1; i <= n; i++) {

            if (!is_scc[i]) {

                // If a vertex i is not a part of any SCC
                // insert it into a new SCC list and check
                // for other vertices whether they can be
                // thr part of thidl ist.
                vector<int> scc;
                scc.push_back(i);

                for (int j = i + 1; j <= n; j++) {

                    // If there is a path from vertex i to
                    // vertex j and vice versa put vertex j
                    // into the current SCC list.
                    if (!is_scc[j] && isPath(i, j, adj)
                        && isPath(j, i, adj)) {
                        is_scc[j] = 1;
                        scc.push_back(j);
                    }
                }

                // Insert the SCC containing vertex i into
                // the final list.
                ans.push_back(scc);
            }
        }
        return ans;
    }
};

// Driver Code Starts

int main()
{

    GFG obj;
    int V = 5;
    vector<vector<int> > edges{
        { 1, 3 }, { 1, 4 }, { 2, 1 }, { 3, 2 }, { 4, 5 }
    };
    vector<vector<int> > ans = obj.findSCC(V, edges);
    cout << "Strongly Connected Components are:\n";
    for (auto x : ans) {
        for (auto y : x) {
            cout << y << " ";
        }
        cout << "\n";
    }
}
Java
import java.util.ArrayList;
import java.util.List;

class GFG {

    // dfs Function to reach destination
    boolean dfs(int curr, int des, List<List<Integer>> adj,
                List<Integer> vis) {

        // If curr node is destination return true
        if (curr == des) {
            return true;
        }
        vis.set(curr, 1);
        for (int x : adj.get(curr)) {
            if (vis.get(x) == 0) {
                if (dfs(x, des, adj, vis)) {
                    return true;
                }
            }
        }
        return false;
    }

    // To tell whether there is path from source to
    // destination
    boolean isPath(int src, int des, List<List<Integer>> adj) {
        List<Integer> vis = new ArrayList<>(adj.size() + 1);
        for (int i = 0; i <= adj.size(); i++) {
            vis.add(0);
        }
        return dfs(src, des, adj, vis);
    }

    // Function to return all the strongly connected
    // component of a graph.
    List<List<Integer>> findSCC(int n, List<List<Integer>> a) {
        // Stores all the strongly connected components.
        List<List<Integer>> ans = new ArrayList<>();

        // Stores whether a vertex is a part of any Strongly
        // Connected Component
        List<Integer> is_scc = new ArrayList<>(n + 1);
        for (int i = 0; i <= n; i++) {
            is_scc.add(0);
        }

        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            adj.add(new ArrayList<>());
        }

        for (List<Integer> edge : a) {
            adj.get(edge.get(0)).add(edge.get(1));
        }

        // Traversing all the vertices
        for (int i = 1; i <= n; i++) {

            if (is_scc.get(i) == 0) {

                // If a vertex i is not a part of any SCC
                // insert it into a new SCC list and check
                // for other vertices whether they can be
                // the part of this list.
                List<Integer> scc = new ArrayList<>();
                scc.add(i);

                for (int j = i + 1; j <= n; j++) {

                    // If there is a path from vertex i to
                    // vertex j and vice versa, put vertex j
                    // into the current SCC list.
                    if (is_scc.get(j) == 0 && isPath(i, j, adj)
                            && isPath(j, i, adj)) {
                        is_scc.set(j, 1);
                        scc.add(j);
                    }
                }

                // Insert the SCC containing vertex i into
                // the final list.
                ans.add(scc);
            }
        }
        return ans;
    }
}

public class Main {

    public static void main(String[] args) {

        GFG obj = new GFG();
        int V = 5;
        List<List<Integer>> edges = new ArrayList<>();
        edges.add(new ArrayList<>(List.of(1, 3)));
        edges.add(new ArrayList<>(List.of(1, 4)));
        edges.add(new ArrayList<>(List.of(2, 1)));
        edges.add(new ArrayList<>(List.of(3, 2)));
        edges.add(new ArrayList<>(List.of(4, 5)));
        List<List<Integer>> ans = obj.findSCC(V, edges);
        System.out.println("Strongly Connected Components are:");
        for (List<Integer> x : ans) {
            for (int y : x) {
                System.out.print(y + " ");
            }
            System.out.println();
        }
    }
}

// This code is contributed by shivamgupta310570
Python
class GFG:
    # dfs Function to reach destination
    def dfs(self, curr, des, adj, vis):
        # If current node is the destination, return True
        if curr == des:
            return True
        vis[curr] = 1
        for x in adj[curr]:
            if not vis[x]:
                if self.dfs(x, des, adj, vis):
                    return True
        return False
    
    # To tell whether there is a path from source to destination
    def isPath(self, src, des, adj):
        vis = [0] * (len(adj) + 1)
        return self.dfs(src, des, adj, vis)
    
    # Function to return all the strongly connected components of a graph.
    def findSCC(self, n, a):
        # Stores all the strongly connected components.
        ans = []
        
        # Stores whether a vertex is a part of any Strongly Connected Component
        is_scc = [0] * (n + 1)
        
        adj = [[] for _ in range(n + 1)]
        
        for i in range(len(a)):
            adj[a[i][0]].append(a[i][1])
        
        # Traversing all the vertices
        for i in range(1, n + 1):
            if not is_scc[i]:
                # If a vertex i is not a part of any SCC, insert it into a new SCC list
                # and check for other vertices whether they can be part of this list.
                scc = [i]
                for j in range(i + 1, n + 1):
                    # If there is a path from vertex i to vertex j and vice versa,
                    # put vertex j into the current SCC list.
                    if not is_scc[j] and self.isPath(i, j, adj) and self.isPath(j, i, adj):
                        is_scc[j] = 1
                        scc.append(j)
                # Insert the SCC containing vertex i into the final list.
                ans.append(scc)
        return ans

# Driver Code Starts
if __name__ == "__main__":
    obj = GFG()
    V = 5
    edges = [
        [1, 3], [1, 4], [2, 1], [3, 2], [4, 5]
    ]
    ans = obj.findSCC(V, edges)
    print("Strongly Connected Components are:")
    for x in ans:
        for y in x:
            print(y, end=" ")
        print()
        
# This code is contributed by shivamgupta310570
C#
using System;
using System.Collections.Generic;

class GFG
{
    // dfs Function to reach destination
    public bool Dfs(int curr, int des, List<List<int>> adj, List<int> vis)
    {
        // If curr node is the destination, return true
        if (curr == des)
        {
            return true;
        }
        vis[curr] = 1;
        foreach (var x in adj[curr])
        {
            if (vis[x] == 0)
            {
                if (Dfs(x, des, adj, vis))
                {
                    return true;
                }
            }
        }
        return false;
    }

    // To tell whether there is a path from source to destination
    public bool IsPath(int src, int des, List<List<int>> adj)
    {
        var vis = new List<int>(adj.Count + 1);
        for (int i = 0; i < adj.Count + 1; i++)
        {
            vis.Add(0);
        }
        return Dfs(src, des, adj, vis);
    }

    // Function to return all the strongly connected components of a graph
    public List<List<int>> FindSCC(int n, List<List<int>> a)
    {
        // Stores all the strongly connected components
        var ans = new List<List<int>>();

        // Stores whether a vertex is a part of any Strongly Connected Component
        var isScc = new List<int>(n + 1);
        for (int i = 0; i < n + 1; i++)
        {
            isScc.Add(0);
        }

        var adj = new List<List<int>>(n + 1);
        for (int i = 0; i < n + 1; i++)
        {
            adj.Add(new List<int>());
        }

        for (int i = 0; i < a.Count; i++)
        {
            adj[a[i][0]].Add(a[i][1]);
        }

        // Traversing all the vertices
        for (int i = 1; i <= n; i++)
        {
            if (isScc[i] == 0)
            {
                // If a vertex i is not a part of any SCC
                // insert it into a new SCC list and check
                // for other vertices whether they can be
                // the part of this list.
                var scc = new List<int>();
                scc.Add(i);

                for (int j = i + 1; j <= n; j++)
                {
                    // If there is a path from vertex i to
                    // vertex j and vice versa, put vertex j
                    // into the current SCC list.
                    if (isScc[j] == 0 && IsPath(i, j, adj) && IsPath(j, i, adj))
                    {
                        isScc[j] = 1;
                        scc.Add(j);
                    }
                }

                // Insert the SCC containing vertex i into
                // the final list.
                ans.Add(scc);
            }
        }
        return ans;
    }
}

// Driver Code Starts
class Program
{
    static void Main(string[] args)
    {
        GFG obj = new GFG();
        int V = 5;
        List<List<int>> edges = new List<List<int>>
        {
            new List<int> { 1, 3 }, new List<int> { 1, 4 }, new List<int> { 2, 1 },
            new List<int> { 3, 2 }, new List<int> { 4, 5 }
        };
        List<List<int>> ans = obj.FindSCC(V, edges);
        Console.WriteLine("Strongly Connected Components are:");
        foreach (var x in ans)
        {
            foreach (var y in x)
            {
                Console.Write(y + " ");
            }
            Console.WriteLine();
        }
    }
}


// This code is contributed by shivamgupta310570
JavaScript
class GFG {
    // Function to reach the destination using DFS
    dfs(curr, des, adj, vis) {
        // If the current node is the destination, return true
        if (curr === des) {
            return true;
        }
        vis[curr] = 1;
        for (let x of adj[curr]) {
            if (!vis[x]) {
                if (this.dfs(x, des, adj, vis)) {
                    return true;
                }
            }
        }
        return false;
    }

    // Check whether there is a path from source to destination
    isPath(src, des, adj) {
        const vis = new Array(adj.length + 1).fill(0);
        return this.dfs(src, des, adj, vis);
    }

    // Function to find all strongly connected components of a graph
    findSCC(n, a) {
        // Stores all strongly connected components
        const ans = [];

        // Stores whether a vertex is part of any Strongly Connected Component
        const is_scc = new Array(n + 1).fill(0);
        const adj = new Array(n + 1).fill().map(() => []);

        for (let i = 0; i < a.length; i++) {
            adj[a[i][0]].push(a[i][1]);
        }

        // Traversing all the vertices
        for (let i = 1; i <= n; i++) {
            if (!is_scc[i]) {
                // If a vertex i is not part of any SCC,
                // insert it into a new SCC list and check
                // for other vertices that can be part of this list.
                const scc = [i];
                for (let j = i + 1; j <= n; j++) {
                    // If there is a path from vertex i to
                    // vertex j and vice versa, put vertex j
                    // into the current SCC list.
                    if (!is_scc[j] && this.isPath(i, j, adj) && this.isPath(j, i, adj)) {
                        is_scc[j] = 1;
                        scc.push(j);
                    }
                }
                // Insert the SCC containing vertex i into the final list.
                ans.push(scc);
            }
        }
        return ans;
    }
}

// Driver Code Starts
const obj = new GFG();
const V = 5;
const edges = [
    [1, 3], [1, 4], [2, 1], [3, 2], [4, 5]
];
const ans = obj.findSCC(V, edges);
console.log("Strongly Connected Components are:");
for (let x of ans) {
    console.log(x.join(" "));
}

// This code is contributed by shivamgupta310570

Output
Strongly Connected Components are:
1 2 3 
4 
5 

Time complexity: O(n * (n + m)), because for each pair of vertices we are checking whether a path exists between them.
Auxiliary Space: O(N)

Efficient Approach for Finding Strongly Connected Components (SCCs)

To find SCCs in a graph, we can use algorithms like Kosaraju’s Algorithm or Tarjan’s Algorithm. Let’s explore these algorithms step-by-step.

1. Kosaraju’s Algorithm:

Kosaraju’s Algorithm involves two main phases:

  1. Performing Depth-First Search (DFS) on the Original Graph:
    • We first do a DFS on the original graph and record the finish times of nodes (i.e., the time at which the DFS finishes exploring a node completely).
  2. Performing DFS on the Transposed Graph:
    • We then reverse the direction of all edges in the graph to create the transposed graph.
    • Next, we perform a DFS on the transposed graph, considering nodes in decreasing order of their finish times recorded in the first phase.
    • Each DFS traversal in this phase will give us one SCC.

Here’s a simplified version of Kosaraju’s Algorithm:

  1. DFS on Original Graph: Record finish times.
  2. Transpose the Graph: Reverse all edges.
  3. DFS on Transposed Graph: Process nodes in order of decreasing finish times to find SCCs.

2. Tarjan’s Algorithm:

Tarjan’s Algorithm is more efficient because it finds SCCs in a single DFS pass using a stack and some additional bookkeeping:

  1. DFS Traversal: During the DFS, maintain an index for each node and the smallest index (low-link value) that can be reached from the node.
  2. Stack: Keep track of nodes currently in the recursion stack (part of the current SCC being explored).
  3. Identifying SCCs: When a node’s low-link value equals its index, it means we have found an SCC. Pop all nodes from the stack until we reach the current node.

Here’s a simplified outline of Tarjan’s Algorithm:

  1. Initialize index to 0.
  2. For each unvisited node, perform DFS.
    • Set the node’s index and low-link value.
    • Push the node onto the stack.
    • For each adjacent node, either perform DFS if it’s not visited or update the low-link value if it’s in the stack.
    • If the node’s low-link value equals its index, pop nodes from the stack to form an SCC.

Conclusion

Understanding and finding strongly connected components in a directed graph is essential for many applications in computer science. Kosaraju’s and Tarjan’s algorithms are efficient ways to identify SCCs, each with their own approach and advantages. By mastering these concepts, you can better analyze and optimize the structure and behavior of complex networks.



Previous Article
Next Article

Similar Reads

Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Tarjan's Algorithm to find Strongly Connected Components
A directed graph is strongly connected if there is a path between all pairs of vertices. A strongly connected component (SCC) of a directed graph is a maximal strongly connected subgraph. For example, there are 3 SCCs in the following graph: We have discussed Kosaraju's algorithm for strongly connected components. The previously discussed algorithm
15+ min read
Strongly Connected Components (SCC) in Python
Strongly Connected Components (SCCs) in a directed graph are groups of vertices where each vertex has a path to every other vertex within the same group. SCCs are essential for understanding the connectivity structure of directed graphs. Kosaraju's Algorithm:Kosaraju's algorithm is a popular method for finding SCCs in a directed graph. It consists
3 min read
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices. For example, following is a strongly connected graph. It is easy for undirected graph, we can just do a BFS and DFS starting from any vertex. If BFS or DFS visits all vertices,
13 min read
Strongly Connected Component meaning in DSA
Strongly Connected Component (SCC) is a concept in graph theory, specifically in directed graphs. A subgraph of a directed graph is considered to be an SCC if and only if for every pair of vertices A and B, there exists a path from A to B and a path from B to A. Properties of Strongly Connected Component:An SCC is a maximal strongly connected subgr
2 min read
Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pairs of vertices. There are different methods to check the connectivity of directed graph but one of the optimized method is Kosaraju’s DFS based simple algorithm. Kosaraju’s BFS based simple al
14 min read
Minimum edges required to make a Directed Graph Strongly Connected
Given a Directed graph of N vertices and M edges, the task is to find the minimum number of edges required to make the given graph Strongly Connected. Examples:  Input: N = 3, M = 3, source[] = {1, 2, 1}, destination[] = {2, 3, 3} Output: 1 Explanation: Adding a directed edge joining the pair of vertices {3, 1} makes the graph strongly connected. H
10 min read
Number of connected components in a 2-D matrix of strings
Given a 2-D matrix mat[][] the task is to count the number of connected components in the matrix. A connected component is formed by all equal elements that share some common side with at least one other element of the same component.Examples: Input: mat[][] = {"bbba", "baaa"} Output: 2 The two connected components are: bbb b AND a aaa Input: mat[]
8 min read
Check if a Tree can be split into K equal connected components
Given Adjacency List representation of a tree and an integer K., the task is to find whether the given tree can be split into K equal Connected Components or not.Note: Two connected components are said to be equal if they contain equal number of nodes. Examples: Input: N = 15, K = 5 Below is the given tree with Number nodes = 15 Output: YES Explana
9 min read
Check if the length of all connected components is a Fibonacci number
Given an undirected graph with V vertices and E edges, the task is to find all the connected components of the graph and check if each of their lengths are a Fibonacci number or not. For example, consider the following graph. As depicted above, the lengths of the connected components are 2, 3, and 2 which are Fibonacci numbers. Examples: Input: E =
15+ min read
Count of unique lengths of connected components for an undirected graph using STL
Given an undirected graph, the task is to find the size of each connected component and print the number of unique sizes of connected components As depicted above, the count(size of the connected component) associated with the connected components is 2, 3, and 2. Now, the unique count of the components is 2 and 3. Hence, the expected result is Coun
10 min read
Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
Given a binary-valued Undirected Graph with V vertices and E edges, the task is to find the maximum decimal equivalent among all the connected components of the graph. A binary-valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: 3 Explanation: Decimal equivalents of the c
14 min read
Largest subarray sum of all connected components in undirected graph
Given an undirected graph with V vertices and E edges, the task is to find the maximum contiguous subarray sum among all the connected components of the graph. Examples: Input: E = 4, V = 7 Output: Maximum subarray sum among all connected components = 5 Explanation: Connected Components and maximum subarray sums are as follows: [3, 2]: Maximum suba
14 min read
Octal equivalents of connected components in Binary valued graph
Given a binary valued undirected graph with V vertices and E edges, the task is to find the octal equivalents of all the connected components of the graph. A binary valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: Chain = 0 1 Octal equivalent = 1 Chain = 0 0 0 Octal eq
15+ min read
Queries to count connected components after removal of a vertex from a Tree
Given a Tree consisting of N nodes valued in the range [0, N) and an array Queries[] of Q integers consisting of values in the range [0, N). The task for each query is to remove the vertex valued Q[i] and count the connected components in the resulting graph. Examples: Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Que
8 min read
Maximum number of edges to be removed to contain exactly K connected components in the Graph
Given an undirected graph G with N nodes, M edges, and an integer K, the task is to find the maximum count of edges that can be removed such that there remains exactly K connected components after the removal of edges. If the graph cannot contain K connect components, print -1. Examples: Input: N = 4, M = 3, K = 2, Edges[][] = {{1, 2}, {2, 3}, {3,
9 min read
Queries to find number of connected grid components of given sizes in a Matrix
Given a matrix mat[][] containing only of 0s and 1s, and an array queries[], the task is for each query, say k, is to find the number of connected grid components (cells consisting of 1s) of size k. Note: Two cells are connected if they share an edge in the direction up, down, left, and right not diagonal. Example: Input: mat[][] = [[1 1 1 1 1 1],
14 min read
Smallest vertex in the connected components of all the vertices in given undirect graph
Given an undirected graph G(V, E) consisting of2 N vertices and M edges, the task is to find the smallest vertex in the connected component of the vertex i for all values of i in the range [1, N]. Examples: Input: N = 5, edges[] = {{1, 2}, {2, 3}, {4, 5}}Output: 1 1 1 4 4Explanation: The given graph can be divided into a set of two connected compon
11 min read
Find Weakly Connected Components in a Directed Graph
Weakly Connected Graph: A directed graph 'G = (V, E)' is weakly connected if the underlying undirected graph Ĝ is connected. The underlying undirected graph is the graph Ĝ = (V, Ê) where Ê represents the set of undirected edges that is obtained by removing the arrowheads from the directed edges and making them bidirectional in G. Example: The direc
9 min read
Count of connected components in given graph after removal of given Q vertices
Given an undirected graph g, the task is to find the number of coalitions formed in it after the removal of Q vertices and maximum vertices among all these connected components. A coalition is defined as the number of connected components left after removal of Q vertices i.e vertices being removed from the graph are not considered as part of the co
10 min read
Connected Components in an Undirected Graph
Given an undirected graph, the task is to print all the connected components line by line. Examples: Input: Consider the following graph Output:0 1 23 4Explanation: There are 2 different connected components.They are {0, 1, 2} and {3, 4}. Recommended PracticeNumber of ProvincesTry It! We have discussed algorithms for finding strongly connected comp
14 min read
Minimum and maximum number of connected components
Given array A[] of size N representing graph with N nodes. There is an undirected edge between i and A[i] for 1 <= i <= N. The Task for this problem is to find the minimum and maximum number of connected components in the given graph if it is allowed to add an edge between any two nodes from N nodes as long as each node has a degree at most 2
13 min read
Maximum sum of values of nodes among all connected components of an undirected graph
Given an undirected graph with V vertices and E edges. Every node has been assigned a given value. The task is to find the connected chain with the maximum sum of values among all the connected components in the graph. Examples: Input: V = 7, E = 4 Values = {10, 25, 5, 15, 5, 20, 0}   Output : Max Sum value = 35 Explanation: Component {1, 2} - Valu
15+ min read
Sum of the minimum elements in all connected components of an undirected graph
Given an array A of N numbers where A i represent the value of the (i+1) th node. Also given are M pair of edges where u and v represent the nodes that are connected by an edge. The task is to find the sum of the minimum element in all the connected components of the given undirected graph. If a node has no connectivity to any other node, count it
7 min read
Number of connected components of a graph ( using Disjoint Set Union )
Given an undirected graph G with vertices numbered in the range [0, N] and an array Edges[][] consisting of M edges, the task is to find the total number of connected components in the graph using Disjoint Set Union algorithm. Examples: Input: N = 4, Edges[][] = {{1, 0}, {2, 3}, {3, 4}}Output: 2Explanation: There are only 2 connected components as
7 min read
Minimize the number of weakly connected nodes
Given an undirected graph, task is to find the minimum number of weakly connected nodes after converting this graph into directed one. Weakly Connected Nodes : Nodes which are having 0 indegree(number of incoming edges). Prerequisite : BFS traversal Examples : Input : 4 4 0 1 1 2 2 3 3 0 Output : 0 disconnected components Input : 6 5 1 2 2 3 4 5 4
11 min read
Remove edges connected to a node such that the three given nodes are in different trees
Given a binary tree and 3 nodes a, b and c, the task is to find a node in the tree such that after removing all the edge connected to that node, a, b and c are in three different trees. Given below is a tree with input nodes as c, j and o. In the above tree, if node i gets disconnected from the tree, then the given nodes c, j, and o will be in thre
11 min read
Minimum number of Water to Land conversion to make two islands connected in a Grid
Given a 2D grid arr[][] of ‘W’ and ‘L’ where 'W' denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected. An island is the set of connected ‘L’s. Note: There can be only two disjoint islands. Examples: Input: arr[][] = {{'W',
10 min read
All vertex pairs connected with exactly k edges in a graph
Given a directed graph represented as an adjacency matrix and an integer 'k', the task is to find all the vertex pairs that are connected with exactly 'k' edges. Also, find the number of ways in which the two vertices can be linked in exactly k edges. Examples : Input : k = 3 and graph : 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 Output : 1
15+ min read
Maximum pairs from given Graph where elements belong to different Connected Component
Given a graph with N vertices numbered from 0 to (N-1) and a matrix edges[][] representing the edges of the graph, the task is to find out the maximum number of pairs that can be formed where each element of a pair belongs to different connected components of the graph. Examples: Input: N = 4, edges = {{1, 2}, {2, 3}}Output: 3Explanation: Total nod
7 min read
Article Tags :
Practice Tags :