Problem 278
Knight Minimum Moves
Medium · 20 pts · Breadth-First Search, Matrix
Problem
On an N x N chessboard, a knight moves in an L shape: two squares in one direction and one square in a perpendicular direction, giving up to 8 possible moves, and it must stay on the board. Find the minimum number of moves the knight needs to go from square (R1, C1) to square (R2, C2), with rows and columns numbered from 1 to N. If the target cannot be reached, which can happen on very small boards, print -1. Breadth-first search over the squares, starting from the knight's position, finds the minimum number of moves.
Input
First line: integer N. Second line: R1 C1 R2 C2.
Output
Print the minimum number of moves, or -1.
Constraints
1 <= N <= 1000
Example input
8 1 1 8 8
Example output
6
Explanation
On a standard 8 x 8 board, a knight needs 6 moves to go from one corner, (1, 1), to the opposite corner, (8, 8). No shorter sequence of knight moves reaches it.