Hackerrank - Search - Connected Cells in a Grid

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 at least one other cell 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
The first region has five cells and the second region has one cell. Because we want to print the number of cells in the largest region of the matrix, we print .

Solution

# Enter your code here. Read input from STDIN. Print output to STDOUT

r_max = int(raw_input())
c_max = int(raw_input())
matrix = []
for scan in range(r_max):
    matrix.append(list(map(int , raw_input().split())))
def check(matrix, row, col):
 if row < 0 or col < 0 or row >= r_max or col >= c_max :
  return 0
 if matrix[row][col] == 0:
  return 0
 matrix[row][col] = 0
 size = 1
 for k in range(row-1,row+2):
  for d in range(col-1, col+2):
   if k != row or d != col:
    size += check(matrix,k,d)

 return size

max_reg = 0
for row in range(r_max):
 for col in range(c_max):
  if matrix[row][col] == 1:
   size = check(matrix,row,col)
   max_reg = max(size, max_reg)
print max_reg            

Comments

Best Programming language for machine learning.

Popular posts from this blog

Hackerrank - Implementation - Picking Numbers

Hackerrank - Dynamic Programming - The Coin Change Problem