#abc241f. F - Skate

F - Skate

Score : 500500 points

问题描述

存在一个表示为 HH 行(水平)和 WW 列(垂直)网格的滑冰场。令 (i,j)(i, j) 表示从上数第 ii 行、从左数第 jj 列的方格。

滑冰场内有 NN 个障碍物。第 ii 个障碍物位于坐标 (Xi,Yi)(X_i,Y_i)

在一次移动中,Takahashi 选择向上、向下、向左或向右四个方向之一,并持续移动直到他碰到障碍物为止。 当他碰到障碍物时,他会停在紧靠障碍物前的那个方格。由于滑冰场四周都是悬崖,因此禁止进行会导致永不碰到障碍物的移动。

Takahashi 起始位置为 (sx,sy)(s_x,s_y)。他希望通过若干次移动最终停在坐标 (gx,gy)(g_x,g_y) 处。

求出到达终点 (gx,gy)(g_x, g_y) 所需的最少移动次数。如果无法实现,请报告这一事实。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

There is a skating rink represented by a grid with HH horizontal rows and WW vertical columns. Let (i,j)(i, j) denote the square at the ii-th row from the top and jj-th column from the left.

The skating rink has NN obstacles. The ii-th obstacle is placed at (Xi,Yi)(X_i,Y_i).

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 (sx,sy)(s_x,s_y). He wants to make some number of moves to stop at (gx,gy)(g_x,g_y).

Find the minimum number of moves required to end up at (gx,gy)(g_x, g_y). If it is not possible, report the fact.

Constraints

  • 1H1091\leq H \leq 10^9
  • 1W1091\leq W \leq 10^9
  • 1N1051\leq N \leq 10^5
  • 1sx,gxH1\leq s_x,g_x\leq H
  • 1sy,gyW1\leq s_y,g_y\leq W
  • 1XiH1\leq X_i \leq H
  • 1YiW1\leq Y_i \leq W
  • (sx,sy)(gx,gy)(s_x,s_y)\neq (g_x,g_y)
  • (sx,sy)(Xi,Yi)(s_x,s_y)\neq (X_i,Y_i)
  • (gx,gy)(Xi,Yi)(g_x,g_y)\neq (X_i,Y_i)
  • If iji\neq j, then (Xi,Yi)(Xj,Yj)(X_i,Y_i)\neq (X_j,Y_j).
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

HH WW NN

sxs_x sys_y

gxg_x gyg_y

X1X_1 Y1Y_1

X2X_2 Y2Y_2

\vdots

XNX_N YNY_N

Output

Print the minimum number of moves required to end up at (gx,gy)(g_x,g_y).
If it is impossible to end up there, print -1.

Sample Input 1

7 8 7
3 4
5 6
1 4
2 1
2 8
4 5
5 7
6 2
6 6

Sample Output 1

4

In the figure, (sx,sy)(s_x,s_y) is denoted by S and (gx,gy)(g_x,g_y) 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 (gx,gy)(g_x,g_y) with 44 moves.

Sample Input 2

4 6 2
3 2
3 5
4 5
2 5

Sample Output 2

-1

He must stop at (gx,gy)(g_x,g_y).
Note that just passing through (gx,gy)(g_x,g_y) is not considered to be ending up at the goal.

Sample Input 3

1 10 1
1 5
1 1
1 7

Sample Output 3

-1


If he chooses to move to the left, Takahashi will fall down the cliff after passing through (gx,gy)(g_x,g_y).
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.

update @ 2024/3/10 10:24:01