Time Limit: Java: 10000 ms / Others: 10000 ms
Memory Limit: Java: 32768 KB / Others: 32768 KB
Holedox is a special snake, but its body is not very long. Its lair is like a maze and can be imagined as a rectangle with n*m squares. Each square is either a stone or a vacant place, and only vacant places allow Holedox to move in. Using ordered pair of row and column number of the lair, the square of exit located at (1,1).
Holedox's body, whose length is L, can be represented block by block. And let B1(r1,c1) B2(r2,c2) .. BL(rL,cL) denote its L length body, where Bi is adjacent to Bi+1 in the lair for 1 i L-1, and B1 is its head, BL is its tail.
To move in the lair, Holedox chooses an adjacent vacant square of its head, which is neither a stone nor occupied by its body. Then it moves the head into the vacant square, and at the same time, each other block of its body is moved into the square occupied by the corresponding previous block.
For example, in the Figure 2, at the beginning the body of Holedox can be represented as B1(4,1) B2(4,2) B3(3,2)B4(3,1). During the next step, observing that B1'(5,1) is the only square that the head can be moved into, Holedox moves its head into B1'(5,1), then moves B2 into B1, B3 into B2, and B4 into B3. Thus after one step, the body of Holedox locates in B1(5,1)B2(4,1)B3(4,2) B4(3,2) (see the Figure 3).
Given the map of the lair and the original location of each block of Holedox's
body, your task is to write a program to tell the minimal number of steps that
Holedox has to take to move its head to reach the square of exit (1,1).
Case 1: 9 Case 2: -1 Note: In the above sample case, the head of Holedox can follows (4,1)'(5,1)'(5,2)'(5,3)'(4,3)'(4,2)'(4,1)'(3,1)'(2,1)'(1,1) to reach the square of exit with minimal number of step, which is nine.