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

#BS0000437. Đường đi có giá trị nhỏ nhất lớn nhất (Path With Maximum Minimum Value)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đường đi có giá trị nhỏ nhất lớn nhất (Path With Maximum Minimum Value)

Path With Maximum Minimum Value

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A table consists of nn rows and mm columns, numbered from 11 to nn and from 11 to mm, respectively. Cell (i,j)(i,j) contains a nonnegative integer ai,ja_{i,j}.

Starting at (1,1)(1,1), you must reach (n,m)(n,m). In each step, you may move to a cell sharing a side with your current cell in one of the four directions, provided you remain within the table.

The score of a route is the smallest value among all cells visited, including both endpoints. For instance, visiting values 8,4,5,98,4,5,9 gives a score of 44. When both endpoints coincide, the score equals the value of that cell.

Find the greatest score attainable among all valid routes from the starting cell to the destination.

Input

  • The first line contains two integers n,mn,m, the numbers of rows and columns.
  • The next nn lines each contain mm integers; line ii lists values ai,1,ai,2,…,ai,ma_{i,1},a_{i,2},\ldots,a_{i,m} of row ii.

Output

Print one integer: the greatest attainable route score.

Subtasks

  • Subtask 1 (20 points): 1≤n,m≤61\le n,m\le 6; 0≤ai,j≤1090\le a_{i,j}\le 10^9 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.
  • Subtask 2 (30 points): 1≤n,m≤1001\le n,m\le 100; 0≤ai,j≤1000\le a_{i,j}\le 100 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.
  • Subtask 3 (50 points): 1≤n,m≤1001\le n,m\le 100; 0≤ai,j≤1090\le a_{i,j}\le 10^9 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.

Examples

Example 1

Input

3 3
5 4 5
1 2 6
7 4 6

Output

4

Explanation

The route (1,1),(1,2),(1,3),(2,3),(3,3)(1,1),(1,2),(1,3),(2,3),(3,3) has values 5,4,5,6,65,4,5,6,6, giving score 44. A score of at least 55 is impossible: the two neighbors of the start have values 44 and 11.

Illustration

Example 2

Input

2 6
2 2 1 2 2 2
1 2 2 2 1 2

Output

2

Explanation

Follow the first row to column 22, go down, move right to column 44, go up, move right to column 66, then go down to the destination. Every visited value is 22. The starting value is 22, so no higher score is possible.