Wise Knight
InterviewTime limit1sMemory limit256 MB
Given a knight's start square on an N by N board, find the minimum knight moves to reach each of M target squares.
- Level
Medium5 of 10
- Topics
- BFS, Graph, Shortest path, Matrix
- Solved
- No attempts yet
Problem
A single knight sits at a particular position on an chessboard. Given the positions of opposing pieces, write a program that computes the minimum number of moves the knight needs to capture each opposing piece.
The knight moves as in ordinary chess. When the knight is at , it moves to one of the following eight positions.
, , , , , , ,
When and the knight is at , the reachable positions are shown below. The position of the knight is marked K, and reachable positions are shown in yellow.

For example, suppose , , and the knight is at . If the opposing pieces are at , , and in that order, the minimum number of moves to capture them is 1, 2, and 1. In the figure below, the opposing pieces are marked E. Positions in this problem are written as (row, column).

Input
The first line gives and as natural numbers separated by a space. (, ) The second line gives and , the position of the knight, as natural numbers separated by a space. () Each of the next lines gives and , the position of an opposing piece, as natural numbers separated by a space. ()
All positions given in the input are distinct, and every one of them is a position the knight can reach.
Output
On the first line, print the minimum number of moves needed to capture each opposing piece, separated by spaces.
Print them in the same order in which the opposing pieces were given in the input.