Problem · Breadth First Search
Minimum Knight Moves
Learn this problemProblem 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) → intComplete the function minMoves in the editor with the following parameters:
int n: the width and height of the square boardint startRow: the row of the starting locationint startCol: the column of the starting locationint endRow: the row of the target locationint 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
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)is2.