algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
2 shown · 0/261 solved

Minimum Knight Steps on a Grid

Silver
Asked atGroww
Solve problem →
5000ms256MBAdded Aug 3, 2026Breadth-First Search II

You are given an n x n grid of cells with 0-indexed coordinates (r, c), 0 <= r, c <= n - 1. A piece stands on cell (r1, c1) and moves like a chess knight: in one step it changes one coordinate by 2 and the other by 1 (all eight combinations of signs and axes), as long as it stays on the grid.

Return the minimum number of steps needed to reach cell (r2, c2), or -1 if it cannot be reached.

Note that the start and target may coincide (0 steps), and that on very small grids some cells are unreachable. For example, on a 3 x 3 grid the center cell has no knight moves at all.

Examples

Example 1

Input: n = 8, r1 = 0, c1 = 0, r2 = 7, c2 = 7
Output: 6
Explanation: On the standard 8 x 8 board, six knight steps are needed between opposite corners.

Example 2

Input: n = 8, r1 = 0, c1 = 0, r2 = 1, c2 = 2
Output: 1
Explanation: (1, 2) is one knight step from (0, 0).

Example 3

Input: n = 3, r1 = 0, c1 = 0, r2 = 1, c2 = 1
Output: -1
Explanation: The center of a 3 x 3 grid cannot be reached; no knight step lands there.

Constraints

  • 1≤1 \leq1≤ n ≤1000\leq 1000≤1000
  • 0≤0 \leq0≤ r1, c1, r2, c2 ≤\leq≤ n −1- 1−1

Details

Solved by4 people
Time limit5000ms
Memory256MB
AddedAug 3, 20265 weeks ago
Breadth-First Search II

More like this