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.
Output : 9
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 :
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:
The largest connected component of the grid is :9 . . . . . . . . . 1 1 . . . . . . . 1 1 . . . . . . . 1 . . . . . . . 1 1 . . . . . . 1 1 . . .
- Number of ways to select a node from each connected component
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Strongly Connected Components
- Connected Components in an undirected graph
- Check if a directed graph is connected or not
- Number of connected components in a 2-D matrix of strings
- All vertex pairs connected with exactly k edges in a graph
- Minimize the number of weakly connected nodes
- Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
- Cycles of length n in an undirected and connected graph
- Tarjan's Algorithm to find Strongly Connected Components
- Sum of the minimum elements in all connected components of an undirected graph
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
- Check if a Tree can be split into K equal connected components
- Check if there exists a connected graph that satisfies the given conditions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.