Question:
Consider a matrix with rows and columns, where each cell contains either a or a and any cell containing a is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally; in other words, cell is connected to cells , , , , , , , and , provided that the location exists in the matrix for that .
If one or more filled cells are also connected, they form a region. Note that each cell in a region is connected to zero or more cells in the region but is not necessarily directly connected to all the other cells in the region.
Task
Given an matrix, find and print the number of cells in the largest region in the matrix. Note that there may be more than one region in the matrix.
Input Format
The first line contains an integer, , denoting the number of rows in the matrix.
The second line contains an integer, , denoting the number of columns in the matrix.
Each line of the subsequent lines contains space-separated integers describing the respective values filling each row in the matrix.
Constraints
Output Format
Print the number of cells in the largest region in the given matrix.
Sample Input
4 4 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 0
Sample Output
5
Explanation
The diagram below depicts two regions of the matrix; for each region, the component cells forming the region are marked with an X:
X X 0 0 1 1 0 0
0 X X 0 0 1 1 0
0 0 X 0 0 0 1 0
1 0 0 0 X 0 0 0
CODE:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row =sc.nextInt();
int col = sc.nextInt();
int [][] arr= new int [row][col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
arr[i][j]=sc.nextInt();
}
}
System.out.println(getBiggestRegion(arr));
}
public static int getBiggestRegion(int [][] matrix){
int maxRegion=0;
for(int row=0;row<matrix.length;row++){
for(int col=0;col<matrix[row].length;col++){
if(matrix[row][col]==1){
int size = getRegion(matrix,row,col);
maxRegion = Math.max(size,maxRegion);
}
}
}
return maxRegion;
}
public static int getRegion(int [][] matrix, int row, int col){
if(row<0||col<0||row>=matrix.length||col>=matrix[row].length){
return 0;
}
if (matrix[row][col]==0){
return 0;
}
matrix[row][col]=0;
int size=1;
for (int r=row-1;r<=row+1;r++){ // look for the adjacent neighbors
for(int c=col-1;c<=col+1;c++){
if(r!=row||c!=col){
size+=getRegion(matrix,r,c);
}
}
}
return size;
}
}
Comments
Post a Comment