PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000435. Bơi trong nước dâng (Swim in Rising Water)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Bơi trong nước dâng (Swim in Rising Water)

Swim in Rising Water

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A square terrain consists of nn rows and nn columns, numbered from 11 to nn. Cell (i,j)(i,j) has elevation hi,jh_{i,j}.

Rain causes the water level to rise. At time tt (t≥0t\ge 0), the water level equals tt. A cell is available for swimming when its elevation does not exceed the water level.

You start at cell (1,1)(1,1) and wish to reach cell (n,n)(n,n). A move is allowed only between cells sharing a side (up, down, left or right) within the terrain. Both cells must have elevations at most tt. Swimming between cells takes zero time.

Find the earliest time at which you can swim from the starting cell to the destination.

Input

  • The first line contains an integer nn, the size of the terrain.
  • The next nn lines each contain nn integers; line ii lists elevations hi,1,…,hi,nh_{i,1},\ldots,h_{i,n} of row ii.

Output

Print one integer: the earliest time at which cell (n,n)(n,n) can be reached.

Subtasks

  • Subtask 1 (20 points): 1≤n≤51\le n\le 5; 0≤hi,j<n20\le h_{i,j}<n^2 for all 1≤i,j≤n1\le i,j\le n; all elevations are pairwise distinct.
  • Subtask 2 (30 points): 1≤n≤201\le n\le 20; 0≤hi,j<n20\le h_{i,j}<n^2 for all 1≤i,j≤n1\le i,j\le n; all elevations are pairwise distinct.
  • Subtask 3 (50 points): 1≤n≤501\le n\le 50; 0≤hi,j<n20\le h_{i,j}<n^2 for all 1≤i,j≤n1\le i,j\le n; all elevations are pairwise distinct.

Examples

Input

2
0 2
1 3

Output

3

Explanation

The destination has elevation 33, so it cannot be reached for t<3t<3. At t=3t=3, the cells (1,1),(2,1),(2,2)(1,1),(2,1),(2,2) form a route with elevations 0,1,30,1,3. The earliest time is therefore 33.

Route in example 1

Input

5
0 1 2 3 4
24 23 22 21 5
12 13 14 15 16
11 17 18 19 20
10 9 8 7 6

Output

16

Explanation

At t=16t=16, move along the first row to column 55, down to row 33, left to column 11, down to the last row, and right to the destination. The highest elevation on this route is 1616. For t≤15t\le15, the only usable cell in row 22 is in column 55, and the cell immediately below it has elevation 1616. The destination is unreachable.

Route in example 2