Source : https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid
Consider a matrix 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 the diagram below, the two colored regions show cells connected to the filled cells. Black on white are not connected.
Cells adjacent to filled cells:
If one or more filled cells are also connected, they form a region. Note that each cell in a region is connected to at least one other cell in the region but is not necessarily directly connected to all the other cells in the region.
Regions:
Given an matrix, find and print the number of cells in the largest region in the matrix.
Function Description
Complete the function maxRegion in the editor below. It must return an integer value, the size of the largest region.
maxRegion has the following parameter(s):
- grid: a two dimensional array of integers
Input Format
The first line contains an integer, , the number of rows in the matrix, .
The second line contains an integer, , the number of columns in the matrix.
Each of the following lines contains a row of space-separated integers, .
Constraints
Output Format
Print the number of cells in the largest region in the given matrix.
Sample Input
441 1 0 00 1 1 00 0 1 01 0 0 0
Sample Output
5
Explanation
The diagram below depicts two regions of the matrix:
The first region has five cells and the second region has one cell. We choose the larger region.
Source : https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid
Solution
// Karthikalapati.blogspot.com | |
// Tips: | |
// - Instead of using a "boolean[][] visited" array, we alter our original grid | |
// - Dont create a 2-D "Point" or "Cell" class. It's not necessary. | |
static int maxRegion(int[][] grid) { | |
final int rows = grid.length; | |
final int cols = grid[0].length; | |
int maxRegion = 0; | |
for (int row = 0; row < rows; row++) { | |
for (int col = 0; col < cols; col++) { | |
/* Find the largest region from the current cell */ | |
if (grid[row][col] == 1) { | |
int size = findLargestRegion(grid, row, col, rows, cols); | |
maxRegion = Math.max(maxRegion, size); | |
} | |
} | |
} | |
return maxRegion; | |
} | |
private static int findLargestRegion(int [][] grid, int row, int col, int rows, int cols) { | |
/* Put boundary checks here (at top of recursive call), instead of before doing recursive call */ | |
if (row < 0 || row >= rows || col < 0 || col >= cols || grid == null || grid[row][col] == 0) { | |
return 0; | |
} | |
grid[row][col] = 0; // we alter the original matrix here | |
int size = 1; // 1 accounts for our size | |
/* Recursively search neighbors */ | |
for (int r = row - 1; r <= row + 1; r++) { | |
for (int c = col - 1; c <= col + 1; c++) { | |
size += findLargestRegion(grid, r, c, rows, cols); | |
} | |
} | |
return size; | |
} |
No comments:
Post a Comment