This page is still under construction.

Parts of this page are still being built. What you see may change.

Tractor

Time limit1sMemory limit128 MB

Summary
Find the smallest cost c so that a connected region of at least half the N x N grid is reachable using only steps whose elevation difference is at most c.
Level

Medium6 of 10

Topics
Binary search, Union-find, Graph, Sorting
Solved
No attempts yet

Problem

One of Farmer John's fields is especially hilly, and he wants to buy a new tractor to drive around on it. The field is given as an N×NN \times N grid of non-negative integer elevations (1≤N≤5001 \le N \le 500); the value in each cell is that cell's elevation.

A tractor may move only one step at a time, to a cell adjacent to the north, east, south, or west. If you buy a tractor of cost cc, it can move freely between any two adjacent cells whose elevation difference is at most cc (a step across an elevation difference greater than cc is impossible).

Farmer John wants to be able to start from some cell and visit at least half of all the cells in the field (rounded up if the number of cells is odd). Compute the minimum cost of a tractor that makes this possible.

Input

  • Line 1: the integer NN.
  • Lines 2 to N+1N+1: each line contains NN space-separated non-negative integers describing one row of the field. Each elevation is at most 1,000,000.

Output

  • Print a single line with the minimum cost of a tractor able to drive around at least half of the field.

Hint

In the example input the field is a 5×55 \times 5 grid, so the tractor must visit at least 13 of the 25 cells. A tractor of cost 3 can move between elevation 0 and elevation 3, so it can reach the region of cells at elevation 0 together with the region of cells at elevation 3. Together these make up at least half of the field, so the answer is 3.

Examples1

  1. Example 1

    Input
    5
    0 0 0 3 3
    0 0 0 0 3
    0 9 9 3 3
    9 9 9 3 3
    9 9 9 9 3
    
    Expected output
    3