Plumbing the Pond

Interview

Time limit1sMemory limit128 MB

Summary
Given a grid of depth readings, find the largest positive value that appears in at least two cells adjacent horizontally, vertically, or diagonally.
Level

Easy3 of 10

Topics
Array, Implementation, Brute force, Matrix
Solved
No attempts yet

Problem

Bessie drinks water from a pond in the northwest part of the farm. The pond has an interesting bottom: it is full of little hills and valleys, and she wonders how deep it is.

She trolls across the pond in her little boat using a very old radar set that tends to produce spurious readings. Because the deepest part of the pond is relatively flat, she decides to trust a large depth value only if the same value also appears in an adjacent reading.

The pond is modeled as an R×CR \times C grid (1≤R≤501 \le R \le 50, 1≤C≤501 \le C \le 50) of depth readings Dr,cD_{r,c} (0≤Dr,c≤1,000,0000 \le D_{r,c} \le 1{,}000{,}000). A reading of 00 marks a cell that is not part of the pond; a reading of 1010 means "depth of 1010".

Two cells are adjacent if one lies in any of the (up to eight) cells that border the other horizontally, vertically, or diagonally. Find the greatest depth value that appears in at least two adjacent cells. It is guaranteed that at least one pair of equal, positive, adjacent readings exists.

Input

  • Line 1: Two space-separated integers RR and CC.
  • Lines 2 to R+1R+1: line i+1i+1 contains the CC space-separated depth readings of row ii: Di,1,Di,2,…,Di,CD_{i,1}, D_{i,2}, \dots, D_{i,C}.

Output

  • Line 1: A single integer, the depth of the pond determined by Bessie's rule.

Hint

The deepest single reading need not be the answer. Only depths that occur in two adjacent cells are candidates, and the answer is the largest such candidate. A value that appears several times but never in two adjacent cells does not qualify.

Examples1

  1. Example 1

    Input
    4 3
    0 1 0
    1 2 0
    1 5 1
    2 3 4
    
    Expected output
    1