Mountain Passage
InterviewTime limit1sMemory limit128 MB
Find the minimum count of steps that touch an elevation above the start height, moving on an n by n grid with height changes limited to 2 per step.
- Level
Medium6 of 10
- Topics
- Graph, Shortest path, Heap, DFS
- Solved
- No attempts yet
Problem
A mountain climber named Alp stands at the northwest corner of a square patch of mountainous terrain and wants to find a passage to the opposite (southeast) corner.
Alp currently stands at an elevation at which oxygen is not needed. At any elevation strictly higher than this starting elevation, oxygen is required. When oxygen is required, it is consumed at a rate of one unit per horizontal step.
The northwest corner is at position and the southeast corner is at position . The elevation of every point with is an integer.
Alp travels in a series of horizontal steps. Each step moves Alp one unit north, south, east, or west. Alp must stay inside the square region and cannot climb or descend more than units of elevation in a single step. If the elevation at the beginning of a step or at the end of a step requires oxygen, Alp consumes one unit of oxygen during that step.
Report the minimum number of units of oxygen Alp must consume to travel from to , or report that no such passage exists.
Input
The first line contains a positive integer : the number of trips Alp must make.
Each trip is described as follows. The first line of a trip contains an integer (), the side length of the square terrain. The next lines each contain a single integer giving the elevation of one point. The elevations are listed in this order:
.
Output
For each trip, print a single line.
If a passage exists, print the minimum number of units of oxygen consumed. If no passage exists, print the message CANNOT MAKE THE TRIP.
Separate the output lines for consecutive trips with a single blank line.