Hiking
InterviewTime limit3sMemory limit256 MB
Find the cheapest 8-direction path from the start to the highest cell of a height grid where flat steps cost 1 and a height change of d costs (d+1) squared.
- Level
Medium4 of 10
- Topics
- Shortest path, Graph, Matrix
- Solved
- No attempts yet
Problem
You like adventure, and hiking is one of your favorite hobbies. A novice is joining you on this trip, so you want to pick the easiest route on the map of the area.
The hiking area is a grid with rows and columns. Each cell is identified by its row number and column number, where is the top-left cell and is the bottom-right cell. You are given a map that lists the height of every cell, together with the starting cell of your trip.
The difficulty of a route is the total energy spent on it. From one cell you can move to an adjacent cell in any of the eight directions: up, left, down, right and the four diagonals. You cannot leave the map, and you cannot enter a dangerous cell.
Moving to a cell of the same height spends 1 unit of energy. Moving to a cell that is units higher or lower spends units of energy.
You and your friend want to reach the highest cell in the grid. There is exactly one highest cell. Find the difficulty of the easiest route, the route that spends the least energy.
Input
The first line contains the number of test cases . ()
Each test case is given in the following format.
- The first line contains the height and the width of the grid. (, )
- The next lines describe the map. Each line is a string of characters. Each character is a digit from 0 to 9 giving the height of that cell, or
#marking a dangerous cell. The digit 9 is the highest. - The last line contains the starting position and . (, ) The starting cell is not a dangerous cell.
Output
For each test case, print the energy needed for the easiest route on its own line. If there is no route from the starting position to the highest cell, print NO.
Hint
In the first example the easiest route is (0, 0) -> (1, 0) -> (2, 1) -> (2, 2) -> (2, 3). The energy spent on the four moves is 1, 4, 4 and 4.