#K34917. Largest Single-Type Square in a Garden

    ID: 25416 Type: Default 1000ms 256MiB

Largest Single-Type Square in a Garden

Largest Single-Type Square in a Garden

You are given a garden represented as a grid with R rows and C columns. Each cell of the grid contains an integer which indicates the type of flowering plant present. A value of 0 indicates that the cell is empty (i.e. no plant). All other positive integers represent different types of flowering plants.

Your task is to determine the side length of the largest contiguous square sub-grid (i.e. a square block of cells) that is completely occupied by the same type of flowering plant. Note that the plant type in the sub-grid must be non-zero. If no such square sub-grid exists, output 0.

More formally, you need to find the maximum integer \(\ell\) for which there exists indices \(x\) and \(y\) such that for all \(i, j\) with \(x \leq i < x+\ell\) and \(y \leq j < y+\ell\), the condition \[ grid[i][j] = k \quad \text{and} \quad k \neq 0 \] holds for some plant type \(k\). If no cell with \(k \neq 0\) exists or no square larger than 0 can be found, output 0.

inputFormat

The first line contains two integers R and C separated by a space. This is followed by R lines, each containing C space-separated integers representing the garden grid.

For example:

5 5
1 1 2 2 2
1 1 2 3 3
1 1 2 3 4
1 1 2 3 4
1 1 2 3 4

outputFormat

Output a single integer representing the side length of the largest square sub-grid that contains only one type of non-zero flowering plant. If there is no valid sub-grid, output 0.

For example:

2
## sample
5 5
1 1 2 2 2
1 1 2 3 3
1 1 2 3 4
1 1 2 3 4
1 1 2 3 4
2