Grid Jumps
InterviewTime limit2sMemory limit256 MB
Find the fewest digit-length jumps from the top-left cell to the bottom-right cell of a grid, or print IMPOSSIBLE.
Problem
Each square of an grid holds one digit. From a square holding the digit , a move jumps exactly squares up, down, left, or right, and counts as one move. A move may not leave the grid, and the grid does not wrap from one edge to the opposite one.
Find the minimum number of moves needed to get from the top left square to the bottom right square.
Input
The first line contains two space separated integers and (), the size of the grid. At least one of and is greater than 1.
Each of the next lines contains digits with no spaces. Every digit is between 0 and 9, inclusive.
The first character of the first line is the top left square, and the last character of the last line is the bottom right square.
Output
Print, on a line by itself, the minimum number of moves needed to get from the top left square to the bottom right square. If the bottom right square cannot be reached, print IMPOSSIBLE.