#C2297. Knight Minimum Moves
Knight Minimum Moves
Knight Minimum Moves
The task is to determine the minimum number of moves required for a knight on a chessboard of size N × N to travel from a given start position to a target position. The knight moves in an 'L'-shape: two cells in one direction and one cell in the perpendicular direction.
If the knight cannot reach the target position, the answer should be -1
. Note that if the starting position is the same as the target position, no moves are required (output 0
).
This problem can be effectively solved by a breadth-first search (BFS) algorithm on the chessboard.
inputFormat
The input is read from standard input (stdin). It consists of three lines:
- The first line contains an integer
N
representing the size of the chessboard (which isN × N
). - The second line contains two space-separated integers representing the starting position coordinates.
- The third line contains two space-separated integers representing the target position coordinates.
All positions use 0-indexing.
outputFormat
The output is a single integer printed to standard output (stdout), representing the minimum number of moves required for the knight to reach the target position, or -1
if it is not reachable.
8
0 0
7 7
6