#BS0000436. Đường đi ít gắng sức nhất (Path With Minimum Effort)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đườ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 rows and columns. Cell has height . Rows are numbered from to , and columns from to .
You start at cell and want to reach cell . 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 to is . 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 .
Find the smallest possible effort of a route from the starting cell to the destination.
Input
- The first line contains two integers , the numbers of rows and columns.
- The next lines each contain integers; line lists the heights of row .
Output
Print one integer: the minimum effort of a route.
Subtasks
- Subtask 1 (20 points): ; for all , .
- Subtask 2 (30 points): ; for all , .
- Subtask 3 (50 points): ; for all , .
Examples
Input
3 3
1 2 2
3 8 2
5 3 5
Output
2
Explanation
The route visits heights . Each of its four differences equals . With a limit of , only the first row and cell can be reached from the start; the destination is unreachable. The answer is .

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 , and every step has difference . Effort is impossible because both neighbors of the starting cell have heights different from .

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 , right to column , up to row , right to column , and down to the destination. Every cell on this route has height , giving effort . No effort can be negative.
