#BS0000431. Khám phá hang động (Cave Exploration)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Khám phá hang động (Cave Exploration)
Cave Exploration
Source: Kattis
Version: Phuoc Hung OJ Extended
Problem Statement
During the rainy season, a goldfish named Orange is trapped at the bottom of a cave in Thailand. The water rises by exactly one meter every hour. Orange can swim instantaneously between adjacent submerged locations, but cannot cross rocks protruding above the water.
The cave is an grid whose rows and columns are numbered from to . The rock at cell is meters high. A cell is submerged when the water level is at least one meter above its rock height. Initially the water is one meter high, and Orange is at cell , whose rock height is zero.
Orange can swim up, down, left or right to an adjacent cell if both cells are submerged. Diagonal moves and moves outside the grid are forbidden. The only exit is cell .
Find the minimum number of hours before Orange can swim from the starting cell to the exit. Swimming takes no time, so only the waiting time for the rising water matters.
Input
The first line contains an integer , the grid size.
The next lines each contain integers. Line of this block contains , the rock heights in row ().
Output
Print a single integer: the minimum number of hours before Orange can reach the exit.
Subtasks
- Subtask 1 (20 points): ; for all ; .
- Subtask 2 (30 points): ; for all ; .
- Subtask 3 (50 points): ; for all ; .
Examples
Input
2
0 3
2 4
Output
4
Explanation
The grid has two rows and two columns. Orange starts at , of height zero, and the exit has height four. After three hours the water level is four meters, so the exit is not submerged. After four hours the water level is five meters, submerging all four cells. Orange can swim through , whose rock is two meters high, to . Earlier arrival is impossible, so the answer is four.
Input
5
0 2 3 10 4
10 23 2 21 12
11 10 12 12 16
12 12 18 10 10
10 10 10 11 10
Output
12
Explanation
After eleven hours the water level is twelve meters. The cells with rock heights at most eleven meters that Orange can reach are
$$(0,0),(0,1),(0,2),(0,3),(0,4),(1,0),(1,2),(2,0),(2,1).$$Every adjacent cell outside this set has rock height at least twelve meters or lies outside the grid. The exit is not yet reachable.
After twelve hours the water level is thirteen meters. Orange can swim down column zero to row four, then right to column four. The rock heights along this route are . The largest is twelve meters, so every cell on this route is submerged. The answer is twelve.