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

#BS0000436. Đường đi ít gắng sức nhất (Path With Minimum Effort)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đường đi ít gắng sức nhất (Path With Minimum Effort)

Path With Minimum Effort

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are preparing for a hiking trip across a rectangular area with nn rows and mm columns. Cell (i,j)(i,j) has height hi,jh_{i,j}. Rows are numbered from 11 to nn, and columns from 11 to mm.

You start at cell (1,1)(1,1) and want to reach cell (n,m)(n,m). Each step must move to a cell sharing a side with the current one, in any of the four directions, without leaving the area.

The effort of a step from (i,j)(i,j) to (u,v)(u,v) is ∣hi,j−hu,v∣|h_{i,j}-h_{u,v}|. The effort of an entire route is the largest effort of any of its steps, rather than their sum. If the start and destination are the same cell, the effort is 00.

Find the smallest possible effort of a route 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 the heights hi,1,…,hi,mh_{i,1},\ldots,h_{i,m} of row ii.

Output

Print one integer: the minimum effort of a route.

Subtasks

  • Subtask 1 (20 points): 1≤n,m≤101\le n,m\le 10; 1≤hi,j≤1001\le h_{i,j}\le 100 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; 1≤hi,j≤1001\le h_{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; 1≤hi,j≤1061\le h_{i,j}\le 10^6 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.

Examples

Input

3 3
1 2 2
3 8 2
5 3 5

Output

2

Explanation

The route (1,1),(2,1),(3,1),(3,2),(3,3)(1,1),(2,1),(3,1),(3,2),(3,3) visits heights 1,3,5,3,51,3,5,3,5. Each of its four differences equals 22. With a limit of 11, only the first row and cell (2,3)(2,3) can be reached from the start; the destination is unreachable. The answer is 22.

Route in example 1

Input

3 3
1 2 3
3 8 4
5 3 5

Output

1

Explanation

Move right twice and then down twice. The heights are 1,2,3,4,51,2,3,4,5, and every step has difference 11. Effort 00 is impossible because both neighbors of the starting cell have heights different from 11.

Route in example 2

Input

5 5
1 2 1 1 1
1 2 1 2 1
1 2 1 2 1
1 2 1 2 1
1 1 1 2 1

Output

0

Explanation

Go down column 11, right to column 33, up to row 11, right to column 55, and down to the destination. Every cell on this route has height 11, giving effort 00. No effort can be negative.

Route in example 3