#K36632. Highest Possible Visibility Height

    ID: 25798 Type: Default 1000ms 256MiB

Highest Possible Visibility Height

Highest Possible Visibility Height

You are given a grid with R rows and C columns. Each cell in the grid contains an integer. A cell value of \(-1\) represents a camera, while any other non-negative integer represents a wall with that height.

Your task is to determine the highest possible visibility height for the cameras in the grid. In other words, if the grid contains at least one camera and at least one wall, compute the minimum wall height among all walls; this is the maximum height that a camera can have without its view being obstructed by a wall. If the grid does not contain any cameras or if there are no walls present, output \(-1\).

Formally, let the grid be represented as an \(R \times C\) matrix \(A\), and define the set of wall heights as \(W = \{ A[i][j] \mid A[i][j] \neq -1 \}\). If there exists at least one cell with \(A[i][j] = -1\) (i.e. at least one camera) and \(W\) is non-empty, then output \(\min(W)\); otherwise, output \(-1\).

inputFormat

The input is read from stdin and has the following format:

R C
row1_value1 row1_value2 ... row1_valueC
row2_value1 row2_value2 ... row2_valueC
...
rowR_value1 rowR_value2 ... rowR_valueC

Where:

  • R is the number of rows in the grid.
  • C is the number of columns in the grid.
  • Each of the next R lines contains C space-separated integers representing the grid.

outputFormat

The output is read from stdout and consists of a single integer, which is the highest possible visibility height for the cameras according to the rule described above. If it is not possible to determine such a height, output \(-1\).

## sample
3 3
2 -1 3
4 1 -1
5 7 6
1