Matrix Neighbors SumMedium

Matrix Neighbors Sum

MediumPractice library · +20 XPmatrixbfshash map

Given a binary matrix (containing only 0s and 1s), find the maximum sum of neighbors for any cell containing a 1. The neighbors of a cell are the cells directly adjacent to it (up, down, left, right). A cell's sum of neighbors is the count of adjacent cells that also contain a 1. If no 1s exist in the matrix, the answer is 0.

Input

The first line contains two integers R and C, the number of rows and columns. The following R lines each contain C integers (0 or 1), representing the matrix.

Output

Print a single integer: the maximum sum of neighbors for any cell containing a 1.

Constraints

1 <= R, C <= 1000. The total number of cells R*C is at most 1,000,000. Matrix elements are 0 or 1.

Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
3 3
1 1 0
1 0 1
0 1 1
Output
2

The cell at (0,0) has one neighbor (0,1) with value 1. The cell at (0,1) has two neighbors (0,0) and (1,0) with value 1. The cell at (1,0) has two neighbors (0,1) and (2,1) with value 1. The cell at (1,2) has one neighbor (2,2) with value 1. The cell at (2,1) has two neighbors (1,0) and (2,2) with v

Example 2

Input
2 2
1 1
1 1
Output
2

All cells are 1. Each cell has exactly 2 neighbors. Max sum is 2.

Hints