#K58362. Minimum Moves to Reach Destination

    ID: 30626 Type: Default 1000ms 256MiB

Minimum Moves to Reach Destination

Minimum Moves to Reach Destination

You are given a set of intersections on a 2D plane and a starting point and a destination. From any position (which might or might not be one of the intersections), you can move to any intersection that lies in the same row (i.e. same x-coordinate) or in the same column (i.e. same y-coordinate), provided the intersection is not the current position. The cost of a move is 1. Your task is to determine the minimum number of moves required to reach the destination by moving only between these intersections. If it is impossible to reach the destination via these moves, output -1.

Note: The starting point can be located anywhere; however, valid moves are only allowed to the given intersections. If the starting point is the same as the destination, the answer is 0.

Formal Description:

Let \( (s_x, s_y) \) be the starting point and \( (e_x, e_y) \) be the destination. There are \( n \) intersections given by \( (x_i, y_i) \) for \( i = 1, 2, \ldots, n \). A move is allowed from \( (x, y) \) to an intersection \( (x_i, y_i) \) if and only if either \( x = x_i \) and \( y \ne y_i \) or \( y = y_i \) and \( x \ne x_i \). Determine the minimum number of moves to reach \( (e_x, e_y) \) from \( (s_x, s_y) \) using such moves, or output \( -1 \) if no such sequence of moves exists.

Example:

Input:
5
0 0
2 2
0 1
1 1
1 2
2 1
2 2

Output: 3

</p>

inputFormat

The input is given via standard input (stdin) and has the following format:

  • The first line contains a single integer \( n \) representing the number of intersections.
  • The second line contains two integers \( s_x \) and \( s_y \) representing the coordinates of the starting point.
  • The third line contains two integers \( e_x \) and \( e_y \) representing the coordinates of the destination.
  • The next \( n \) lines each contain two integers representing the coordinates of an intersection.

It is guaranteed that all integers are space-separated.

outputFormat

Output a single integer via standard output (stdout): the minimum number of moves required to reach the destination, or \( -1 \) if it is impossible.

## sample
5
0 0
2 2
0 1
1 1
1 2
2 1
2 2
3