All problems

Problem 752

Swim in Rising Water

Hard · 30 pts · Matrix, Heap, Binary Search, Union Find

Problem

An N × N grid holds a permutation of the numbers 0 to N² - 1, the elevation of each cell. Rain makes the water level equal to t at time t. You can swim between horizontally or vertically neighbouring cells instantly, but only if both cells have elevation at most t. Starting at the top-left cell, find the earliest time at which you can reach the bottom-right cell. This is a minimax path: Dijkstra's algorithm with a min-heap, where a path's cost is the largest elevation on it.

Input

The first line contains N. Each of the next N lines contains N integers.

Output

Print the earliest time to reach the bottom-right cell.

Constraints

1 <= N <= 50; the values form a permutation of 0 .. N² - 1

Example input

2
0 2
1 3

Example output

3

Explanation

In the grid 0 2 / 1 3, the bottom-right cell has elevation 3, so you cannot finish before time 3. At time 3 every cell is open, so the answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Accounts Merge Next: Ninja's Training