Knight Minimum Moves
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) → intExamples
Example 1
n = 9startRow = 4startCol = 4endRow = 4endCol = 8return = 2Use 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 = 1Use 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 = 0Use 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.