#K49102. Maximum Consecutive Gems

    ID: 28568 Type: Default 1000ms 256MiB

Maximum Consecutive Gems

Maximum Consecutive Gems

Given an M×N grid where each cell contains an integer representing a gem type (with 0 representing an empty cell), your task is to find the size of the largest connected group of non-empty gems (i.e., cells with the same non-zero integer) that are adjacent vertically or horizontally.

Formally, for a cell at position \( (i,j) \) in the grid, its neighbors are defined as \( (i-1,j) \), \( (i+1,j) \), \( (i,j-1) \), \( (i,j+1) \). The connectivity is considered only if the neighboring cell has the same gem type (and is non-zero). Empty cells (denoted by 0) are not considered as gems.

The goal is to compute the maximum number of consecutive gems of the same type that can be obtained by performing a depth-first search (DFS) from any unvisited gem cell.

Note: Use DFS or any graph traversal algorithm that suits the problem. The relation for neighbor connectivity is given by:

\[ neighbors = \{(dx,dy) \mid (dx,dy) \in \{(-1,0), (1,0), (0,-1), (0,1)\}\} \]

inputFormat

The first line contains two integers, M and N, representing the number of rows and columns of the grid respectively.

Each of the following M lines contains N space-separated integers representing the grid cells.

outputFormat

Output a single integer representing the maximum number of consecutive gems (cells with the same non-zero value) connected adjacently (up, down, left, right).

## sample
4 4
1 2 2 1
1 2 2 1
0 1 0 0
3 3 3 1
4