← 返回 uber 的题目列表Minimum Knight Moves on an n x n Board (Bounded Grid Variant)
类型:online_judge
Problem: Minimum Knight Moves on a Bounded n x n Board
You are given a finite n x n chessboard. A knight can move from (x, y) to any of the 8 positions:
(x+2, y+1), (x+2, y-1)
(x-2, y+1), (x-2, y-1)
(x+1, y+2), (x+1, y-2)
(x-1, y+2), (x-1, y-2)
Moves that go outside the board are not allowed.
Given start = (sx, sy) and target = (tx, ty) (both within the board), return the minimum number of moves needed to reach target from start, or -1 if it is impossible.
Input (stdin)
One line with 5 integers:
n sx sy tx ty
Output (stdout)
Print one integer: the minimum number of moves (or -1 if unreachable).
Constraints
1 <= n <= 2000
0 <= sx, sy, tx, ty < n
Examples
Input: 8 0 0 7 7 Output: 6
Input: 4 0 0 3 3 Output: 2
Input: 3 0 0 2 2 Output: 4
Input: 2 0 0 1 1 Output: -1
Input: 1 0 0 0 0 Output: 0
Example
Input
8 0 0 7 7
Output
6