Largest connected component on a grid

17 Dec, 2020
Given a grid with different colors in a different cell, each color represented by a different number. The task is to find out the largest connected component on the grid. Largest component grid refers to a maximum set of cells such that you can move from any cell to any other cell in this set by only moving between side-adjacent cells from the set. Examples:  
Input :  
Grid of different colors
Output : 9  
Largest connected component of grid
 
Approach : The approach is to visualize the given grid as a graph with each cell representing a separate node of the graph and each node connected to four other nodes which are to immediately up, down, left, and right of that grid. Now doing a BFS search for every node of the graph, find all the nodes connected to the current node with same color value as the current node. Here is the graph for above example :  
Graph representation of grid
. At every cell (i, j), a BFS can be done. The possible moves from a cell will be either to right, left, top or bottom. Move to only those cells which are in range and are of the same color. It the same nodes have been visited previously, then the largest component value of the grid is stored in result[][] array. Using memoization, reduce the number of BFS on any cell. visited[][] array is used to mark if the cell has been visited previously and count stores the count of the connected component when a BFS is done for every cell. Store the maximum of the count and print the resultant grid using result[][] array. Below is the illustration of the above approach:  
C++
Java
Python3
C#
// CPP program to print the largest// connected component in a grid#include <bits/stdc++.h>using namespace std; const int n = 6;const int m = 8; // stores information about  which cell// are already visited in a particular BFSint visited[n][m]; // result stores the final result gridint result[n][m]; // stores the count of cells in the largest// connected componentint COUNT; // Function checks if a cell is valid i.e it// is inside the grid and equal to the keybool is_valid(int x, int y, int key, int input[n][m]){    if (x < n && y < m && x >= 0 && y >= 0) {        if (visited[x][y] == false && input[x][y] == key)            return true;        else            return false;    }    else        return false;} // BFS to find all cells in// connection with key = input[i][j]void BFS(int x, int y, int i, int j, int input[n][m]){    // terminating case for BFS    if (x != y)        return;     visited[i][j] = 1;    COUNT++;     // x_move and y_move arrays    // are the possible movements    // in x or y direction    int x_move[] = { 0, 0, 1, -1 };    int y_move[] = { 1, -1, 0, 0 };     // checks all four points connected with input[i][j]    for (int u = 0; u < 4; u++)        if (is_valid(i + y_move[u], j + x_move[u], x, input))            BFS(x, y, i + y_move[u], j + x_move[u], input);} // called every time before a BFS// so that visited array is reset to zerovoid reset_visited(){    for (int i = 0; i < n; i++)        for (int j = 0; j < m; j++)            visited[i][j] = 0;} // If a larger connected component// is found this function is called// to store information about that component.void reset_result(int key, int input[n][m]){    for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {            if (visited[i][j] && input[i][j] == key)                result[i][j] = visited[i][j];            else                result[i][j] = 0;        }    }}// function to print the resultvoid print_result(int res){    cout << "The largest connected "         << "component of the grid is :" << res << "\n";     // prints the largest component    for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {            if (result[i][j])                cout << result[i][j] << " ";            else                cout << ". ";        }        cout << "\n";    }} // function to calculate the largest connected// componentvoid computeLargestConnectedGrid(int input[n][m]){    int current_max = INT_MIN;     for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {            reset_visited();            COUNT = 0;             // checking cell to the right            if (j + 1 < m)                BFS(input[i][j], input[i][j + 1], i, j, input);             // updating result            if (COUNT >= current_max) {                current_max = COUNT;                reset_result(input[i][j], input);            }            reset_visited();            COUNT = 0;             // checking cell downwards            if (i + 1 < n)                BFS(input[i][j], input[i + 1][j], i, j, input);             // updating result            if (COUNT >= current_max) {                current_max = COUNT;                reset_result(input[i][j], input);            }        }    }    print_result(current_max);}// Drivers Codeint main(){    int input[n][m] = { { 1, 4, 4, 4, 4, 3, 3, 1 },                        { 2, 1, 1, 4, 3, 3, 1, 1 },                        { 3, 2, 1, 1, 2, 3, 2, 1 },                        { 3, 3, 2, 1, 2, 2, 2, 2 },                        { 3, 1, 3, 1, 1, 4, 4, 4 },                        { 1, 1, 3, 1, 1, 4, 4, 4 } };     // function to compute the largest    // connected component in the grid    computeLargestConnectedGrid(input);    return 0;}
// Java program to print the largest// connected component in a gridimport java.util.*;import java.lang.*;import java.io.*; class GFG{static final int n = 6;static final int m = 8; // stores information about which cell// are already visited in a particular BFSstatic final int visited[][] = new int [n][m]; // result stores the final result gridstatic final int result[][] = new int [n][m]; // stores the count of// cells in the largest// connected componentstatic int COUNT; // Function checks if a cell// is valid i.e it is inside// the grid and equal to the keystatic boolean is_valid(int x, int y,                        int key,                        int input[][]){    if (x < n && y < m &&        x >= 0 && y >= 0)    {        if (visited[x][y] == 0 &&            input[x][y] == key)            return true;        else            return false;    }    else        return false;} // BFS to find all cells in// connection with key = input[i][j]static void BFS(int x, int y, int i,                int j, int input[][]){    // terminating case for BFS    if (x != y)        return;     visited[i][j] = 1;    COUNT++;     // x_move and y_move arrays    // are the possible movements    // in x or y direction    int x_move[] = { 0, 0, 1, -1 };    int y_move[] = { 1, -1, 0, 0 };     // checks all four points    // connected with input[i][j]    for (int u = 0; u < 4; u++)        if ((is_valid(i + y_move[u],             j + x_move[u], x, input)) == true)            BFS(x, y, i + y_move[u],                      j + x_move[u], input);} // called every time before// a BFS so that visited// array is reset to zerostatic void reset_visited(){    for (int i = 0; i < n; i++)        for (int j = 0; j < m; j++)            visited[i][j] = 0;} // If a larger connected component// is found this function is// called to store information// about that component.static void reset_result(int key,                         int input[][]){    for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            if (visited[i][j] ==1 &&                input[i][j] == key)                result[i][j] = visited[i][j];            else                result[i][j] = 0;        }    }} // function to print the resultstatic void print_result(int res){    System.out.println ("The largest connected " +                    "component of the grid is :" +                                            res );     // prints the largest component    for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            if (result[i][j] != 0)                System.out.print(result[i][j] + " ");            else                System.out.print(". ");        }        System.out.println();    }} // function to calculate the// largest connected componentstatic void computeLargestConnectedGrid(int input[][]){    int current_max = Integer.MIN_VALUE;     for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            reset_visited();            COUNT = 0;             // checking cell to the right            if (j + 1 < m)                BFS(input[i][j], input[i][j + 1],                                    i, j, input);             // updating result            if (COUNT >= current_max)            {                current_max = COUNT;                reset_result(input[i][j], input);            }            reset_visited();            COUNT = 0;             // checking cell downwards            if (i + 1 < n)                BFS(input[i][j],                    input[i + 1][j], i, j, input);             // updating result            if (COUNT >= current_max)            {                current_max = COUNT;                reset_result(input[i][j], input);            }        }    }    print_result(current_max);}// Driver Codepublic static void main(String args[]){    int input[][] = {{1, 4, 4, 4, 4, 3, 3, 1},                     {2, 1, 1, 4, 3, 3, 1, 1},                     {3, 2, 1, 1, 2, 3, 2, 1},                     {3, 3, 2, 1, 2, 2, 2, 2},                     {3, 1, 3, 1, 1, 4, 4, 4},                     {1, 1, 3, 1, 1, 4, 4, 4}};     // function to compute the largest    // connected component in the grid    computeLargestConnectedGrid(input);}} // This code is contributed by Subhadeep
# Python3 program to print the largest# connected component in a grid  n = 6;m = 8;  # stores information about  which cell# are already visited in a particular BFSvisited = [[0 for j in range(m)]for i in range(n)]  # result stores the final result gridresult = [[0 for j in range(m)]for i in range(n)]  # stores the count of cells in the largest# connected componentCOUNT = 0  # Function checks if a cell is valid i.e it# is inside the grid and equal to the keydef is_valid(x, y, key, input):     if (x < n and y < m and x >= 0 and y >= 0):        if (visited[x][y] == 0 and input[x][y] == key):            return True;        else:            return False;         else:        return False;  # BFS to find all cells in# connection with key = input[i][j]def BFS(x, y, i, j, input):         global COUNT         # terminating case for BFS    if (x != y):        return;      visited[i][j] = 1;    COUNT += 1      # x_move and y_move arrays    # are the possible movements    # in x or y direction    x_move = [ 0, 0, 1, -1 ]    y_move = [ 1, -1, 0, 0 ]      # checks all four points connected with input[i][j]    for u in range(4):             if (is_valid(i + y_move[u], j + x_move[u], x, input)):            BFS(x, y, i + y_move[u], j + x_move[u], input);  # called every time before a BFS# so that visited array is reset to zerodef reset_visited():     for i in range(n):        for j in range(m):            visited[i][j] = 0  # If a larger connected component# is found this function is called# to store information about that component.def reset_result(key, input):     for i in range(n):        for j in range(m):            if (visited[i][j] != 0 and input[i][j] == key):                result[i][j] = visited[i][j];            else:                result[i][j] = 0;         # function to print the resultdef print_result(res):     print("The largest connected "+          "component of the grid is :" + str(res));      # prints the largest component    for i in range(n):        for j in range(m):            if (result[i][j] != 0):                print(result[i][j], end = ' ')                             else:                print('. ',end = '')                 print()          # function to calculate the largest connected# componentdef computeLargestConnectedGrid(input):     global COUNT    current_max = -10000000000      for i in range(n):        for j in range(m):            reset_visited();            COUNT = 0;              # checking cell to the right            if (j + 1 < m):                BFS(input[i][j], input[i][j + 1], i, j, input);              # updating result            if (COUNT >= current_max):                current_max = COUNT;                reset_result(input[i][j], input);                         reset_visited();            COUNT = 0;              # checking cell downwards            if (i + 1 < n):                BFS(input[i][j], input[i + 1][j], i, j, input);              # updating result            if (COUNT >= current_max):                current_max = COUNT;                reset_result(input[i][j], input);                 print_result(current_max); # Drivers Codeif __name__=='__main__':         input = [ [ 1, 4, 4, 4, 4, 3, 3, 1 ],                        [ 2, 1, 1, 4, 3, 3, 1, 1 ],                        [ 3, 2, 1, 1, 2, 3, 2, 1 ],                        [ 3, 3, 2, 1, 2, 2, 2, 2 ],                        [ 3, 1, 3, 1, 1, 4, 4, 4 ],                        [ 1, 1, 3, 1, 1, 4, 4, 4 ] ];      # function to compute the largest    # connected component in the grid    computeLargestConnectedGrid(input); # This code is contributed by pratham76
// C# program to print the largest// connected component in a gridusing System; class GFG{public const int n = 6;public const int m = 8; // stores information about which cell// are already visited in a particular BFSpublic static readonly int[][] visited =              RectangularArrays.ReturnRectangularIntArray(n, m); // result stores the final result gridpublic static readonly int[][] result =              RectangularArrays.ReturnRectangularIntArray(n, m); // stores the count of cells in the// largest connected componentpublic static int COUNT; // Function checks if a cell is valid i.e// it is inside the grid and equal to the keyinternal static bool is_valid(int x, int y,                              int key, int[][] input){    if (x < n && y < m &&        x >= 0 && y >= 0)    {        if (visited[x][y] == 0 &&            input[x][y] == key)        {            return true;        }        else        {            return false;        }    }    else    {        return false;    }} // BFS to find all cells in// connection with key = input[i][j]public static void BFS(int x, int y, int i,                       int j, int[][] input){    // terminating case for BFS    if (x != y)    {        return;    }     visited[i][j] = 1;    COUNT++;     // x_move and y_move arrays    // are the possible movements    // in x or y direction    int[] x_move = new int[] {0, 0, 1, -1};    int[] y_move = new int[] {1, -1, 0, 0};     // checks all four points    // connected with input[i][j]    for (int u = 0; u < 4; u++)    {        if ((is_valid(i + y_move[u],             j + x_move[u], x, input)) == true)        {            BFS(x, y, i + y_move[u],                j + x_move[u], input);        }    }} // called every time before// a BFS so that visited// array is reset to zerointernal static void reset_visited(){    for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            visited[i][j] = 0;        }    }} // If a larger connected component is// found this function is called to// store information about that component.internal static void reset_result(int key,                                  int[][] input){    for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            if (visited[i][j] == 1 &&                input[i][j] == key)            {                result[i][j] = visited[i][j];            }            else            {                result[i][j] = 0;            }        }    }} // function to print the resultinternal static void print_result(int res){    Console.WriteLine("The largest connected " +                      "component of the grid is :" + res);     // prints the largest component    for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            if (result[i][j] != 0)            {                Console.Write(result[i][j] + " ");            }            else            {                Console.Write(". ");            }        }        Console.WriteLine();    }} // function to calculate the// largest connected componentpublic static void computeLargestConnectedGrid(int[][] input){    int current_max = int.MinValue;     for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            reset_visited();            COUNT = 0;             // checking cell to the right            if (j + 1 < m)            {                BFS(input[i][j], input[i][j + 1],                                    i, j, input);            }             // updating result            if (COUNT >= current_max)            {                current_max = COUNT;                reset_result(input[i][j], input);            }            reset_visited();            COUNT = 0;             // checking cell downwards            if (i + 1 < n)            {                BFS(input[i][j], input[i + 1][j],                                    i, j, input);            }             // updating result            if (COUNT >= current_max)            {                current_max = COUNT;                reset_result(input[i][j], input);            }        }    }    print_result(current_max);} public static class RectangularArrays{    public static int[][] ReturnRectangularIntArray(int size1,                                                    int size2)    {        int[][] newArray = new int[size1][];        for (int array1 = 0; array1 < size1; array1++)        {            newArray[array1] = new int[size2];        }         return newArray;    }} // Driver Codepublic static void Main(string[] args){    int[][] input = new int[][]    {        new int[] {1, 4, 4, 4, 4, 3, 3, 1},        new int[] {2, 1, 1, 4, 3, 3, 1, 1},        new int[] {3, 2, 1, 1, 2, 3, 2, 1},        new int[] {3, 3, 2, 1, 2, 2, 2, 2},        new int[] {3, 1, 3, 1, 1, 4, 4, 4},        new int[] {1, 1, 3, 1, 1, 4, 4, 4}    };     // function to compute the largest    // connected component in the grid    computeLargestConnectedGrid(input);}}// This code is contributed by Shrikant13
The largest connected component of the grid is :9
. . . . . . . . 
. 1 1 . . . . . 
. . 1 1 . . . . 
. . . 1 . . . . 
. . . 1 1 . . . 
. . . 1 1 . . .
 
tufan_gupta2000
shrikanth13
pratham76
Algorithms-Graph Traversals
BFS
Competitive Programming
Graph
Matrix
Pattern Searching
Matrix
Graph
Pattern Searching
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of strings whose prefix match with the given string to a given length k
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
Equal Sum and XOR of three Numbers
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations