atcoder#ABC241F. [ABC241F] Skate
[ABC241F] Skate
Score : points
Problem Statement
There is a skating rink represented by a grid with horizontal rows and vertical columns. Let denote the square at the -th row from the top and -th column from the left.
The skating rink has obstacles. The -th obstacle is placed at .
In a single move, Takahashi chooses one of the four directions, up, down, left, or right, and keeps moving until he hits an obstacle. When he hits an obstacle, he stops at the square right before the obstacle. Since the skating rink is surrounded by cliffs, it is prohibited to start a move in which he will never hit an obstacle.
Takahashi is initially at . He wants to make some number of moves to stop at .
Find the minimum number of moves required to end up at . If it is not possible, report the fact.
Constraints
- If , then .
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the minimum number of moves required to end up at .
If it is impossible to end up there, print -1
.
7 8 7
3 4
5 6
1 4
2 1
2 8
4 5
5 7
6 2
6 6
4
In the figure, is denoted by S
and is denoted by G
.
By moving as $(3,4)\rightarrow(2,4) \rightarrow(2,2) \rightarrow(5,2) \rightarrow(5,6)$, he can end up at with moves.
4 6 2
3 2
3 5
4 5
2 5
-1
He must stop at . Note that just passing through is not considered to be ending up at the goal.
1 10 1
1 5
1 1
1 7
-1
If he chooses to move to the left, Takahashi will fall down the cliff after passing through . Note that it is prohibited to start a move in which he will never hit an obstacle, as the skating rink is surrounded by cliffs.