Problem · Breadth First Search

Minimum Knight Moves

Learn this problem
MediumMcKinsey & CompanyOA

Problem statement

Given an n x n chessboard, determine the minimum number of valid knight moves required to travel from a starting position A to an ending position B. A knight moves either 2 steps in one direction and 1 step perpendicular, or 1 step in one direction and 2 steps perpendicular. If it is impossible to reach the destination, return -1. All moves must be within the boundaries of the board.

Note: Assume positions A and B are given as (row, column) coordinates using 0-based indexing.

Function

minMoves(n: int, startRow: int, startCol: int, endRow: int, endCol: int) → int

Complete the function minMoves in the editor with the following parameters:

  • int n: the width and height of the square board
  • int startRow: the row of the starting location
  • int startCol: the column of the starting location
  • int endRow: the row of the target location
  • int endCol: the column of the target location

Returns

int: the minimum number of valid knight moves required to reach the target location, or -1 if the target cannot be reached.

Examples

Example 1

n = 9startRow = 4startCol = 4endRow = 4endCol = 8return = 2
Example 1 illustration

The chessboard is 9 x 9.

  • Start at the position (startRow, startCol) = (4, 4).
  • Move 1 step up or down, then 2 steps right to reach either the position (3, 6) or (5, 6).
  • Move 2 steps right and 1 step down or up as necessary to reach the position (4, 8).
  • The minimum number of moves to move from the position (4, 4) to the position (4, 8) is 2.

More McKinsey & Company problems

drafts saved locally
public int minMoves(int n, int startRow, int startCol, int endRow, int endCol) {
  // write your code here
}
n9
startRow4
startCol4
endRow4
endCol8
expected2
checking account