Knight's Journey On A Chessboard

Medium

You have a chessboard of size n*n. A knight sits on the board at a position start(x, y). The knight wants to go to another cell end(x, y).

Find the minimum number of moves required to go from the start position to the end position. If this is not possible, return -1.

Example:
knights-journey-chessboard

Testing

Input Format

The first line contains an integer ‘T’ denoting the number of test cases.

For each test case the input has one line containing five space-separated integers - n, start-x, start-y, end-x, end-y.

Output Format

For each test case, the output has a line containing the minimum number of moves required.

Sample Input

4
6 6 1 2 4
2 1 1 1 1
2 1 1 2 2
3 3 3 1 1

Expected Output

3
0
-1
4

Constraints

1 <= T <= 10
1 <= n <= 103
1 <= x, y <= n

Editorial Link: Editorial