Graph Theory: Shortest Path


Submit solution

Points: 10
Time limit: 3.0s
Memory limit: 128M

Problem type

You are given a \(N \times N\) chessboard with both axis labelled from \(1\) to \(N\). What is the fewest number of knight moves from cell \((A, B)\) to cell \((C, D)\)?

Input Specification

The first line of the input will contain an integer \(N\) \((4 \le N \le 1000)\), indicating the size of the board.

The second line will contain two integers \(A\) and \(B\) \((1 \le A, B \le N)\), representing the knight's starting cell.

The third line will contain two integers \(C\) and \(D\) \((1 \le C, D \le N)\), representing the knight's destination cell.

Output Specification

Output an integer, representing the fewest number of moves required to reach cell \((C, D)\) from cell \((A, B)\).

Sample Input 1

7
2 1
5 3

Sample Output 1

3

Sample Explanation 1

The following image shows the board found in the sample input. One of the shortest paths can be denoted as (2, 1) => (3, 3) => (4, 5) => (5, 3), requiring \(3\) moves.

7
6
5
4
3\((C, D)\)
2
1\((A, B)\)
1234567

Comments

There are no comments at the moment.