FastPrepKnight Minimum Moves

Knight Minimum Moves

IMC Trading logoIMC Trading● MediumNEW GRADOA
Learn

Problem statement

A knight starts at (startRow,startCol) on a square board with n rows and n columns. Coordinates are zero-based.

Each move changes one coordinate by 2 and the other by 1, independently choosing either sign. Every landing square must remain inside the board.

Return the minimum number of moves to (endRow,endCol), or -1 if the target cannot be reached. The board has no obstacles or other pieces.

Function

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

Examples

Example 1

n = 9startRow = 4startCol = 4endRow = 4endCol = 8return = 2

Use legal two-by-one knight jumps that stay inside the square board. No obstacle or bishop is present.

Example 2

n = 4startRow = 0startCol = 0endRow = 1endCol = 2return = 1

Use legal two-by-one knight jumps that stay inside the square board. No obstacle or bishop is present.

Example 3

n = 4startRow = 1startCol = 1endRow = 1endCol = 1return = 0

Use legal two-by-one knight jumps that stay inside the square board. No obstacle or bishop is present.

Constraints

  • 4 <= n <= 150
  • All start and end coordinates satisfy 0 <= coordinate < n.

More IMC Trading problems

See IMC Trading hiring insights
public int minMoves(int n, int startRow, int startCol, int endRow, int endCol) {
    // Write your solution here.
}
n9
startRow4
startCol4
endRow4
endCol8
expected2
Checking account…