2Brute2Best
🔥0

Minimum Steps to Reach Target by a Knight

Medium·GeeksforGeeksBasic Anchor
GeeksforGeeks
30-Second Mental ModelGraph BFS, Implicit graph / state BFS
Complexity:O(8^K)→O(N²)
Key Insight

Treat each square as a node and each legal knight move as an edge. Run BFS from the start square. Give a square its distance the moment it is pushed, so it enters the queue only once. The first distance written for a square is its shortest distance.

Core Validity Invariant

A square's distance is set the first time it is pushed, and it is never changed after that. Every square is pushed once, so the queue never holds the same square twice.

01

Problem

You have an N × N chessboard. A knight stands on one square, and you want to move it to a target square. Rows and columns are numbered from 1 to N, so the top-left square is (1, 1).

A knight moves in an L shape: two squares in one direction, then one square sideways. From a square it has up to 8 moves. A move must stay on the board.

Return the fewest moves the knight needs to reach the target. If the knight already stands on the target, the answer is 0. If the target can never be reached, return -1.

Input

Three values: N, the size of the board; knightPos = [row, column], where the knight starts; targetPos = [row, column], where it must go. Both positions use 1-indexed numbers.

Output

One number: the minimum number of knight moves, or -1 if the target cannot be reached.

Example 1
Input: N = 8, knightPos = [1, 1], targetPos = [8, 8]
Output: 6

Going from one corner of an 8 × 8 board to the opposite corner takes 6 knight moves.

Example 2
Input: N = 6, knightPos = [1, 1], targetPos = [6, 5]
Output: 3

One route is (1,1) → (2,3) → (4,4) → (6,5). Each step is a legal L-shaped jump, and no route with 2 moves exists.

Example 3
Input: N = 4, knightPos = [2, 2], targetPos = [2, 2]
Output: 0

The knight is already on the target, so no moves are needed.

Example 4
Input: N = 3, knightPos = [1, 1], targetPos = [2, 2]
Output: -1

The centre of a 3 × 3 board has no legal knight move, and no knight move lands on it, so it can never be reached.

Constraints
  • • The board is N × N, and both positions are inside it: 1 ≤ row, column ≤ N.
  • • Positions are 1-indexed. Convert them to array indexes before you use them.
  • • On a board of 4 × 4 or bigger every square can be reached. Only very small boards (3 × 3 or less) can leave a square unreachable.
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.

  1. 1.

    A knight move changes the square in one fixed way. How many squares can the knight reach in one move from the middle of the board?

  2. 2.

    If I try every sequence of moves, how fast does the number of sequences grow with each extra move?

  3. 3.

    Is the shortest route always the one that gets closer to the target at every move?

  4. 4.

    If the knight has already reached a square, does a shortest route ever need to come back to it?

  5. 5.

    If I explore from the start in rings, first every square one move away, then two moves away, what changes when I reach the target?

03

Brute force approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceTry all move sequences of length 0, 1, 2, … until one lands on the targetO(8^K)O(K)
OptimalVisit squares in rings from the start; the first time the target is popped gives the answerO(N²)O(N²)
09

Why does this belong to this pattern?

Clues in the problem statement
  • “fewest moves”Every move costs 1, so a question about the fewest moves is a shortest-path question. With equal costs, BFS gives the answer.
  • “knight on a board”Each square is a state, and each legal jump is an edge. The graph is never built in full; the 8 jumps are worked out from the current square.
  • “reach the target”There is only one target, so the search can stop as soon as the target leaves the queue.
Implicit graph (squares are nodes)+every edge costs 1+fewest edges → BFS→Graph BFS, Implicit graph / state BFS

This is the anchor of the sub-pattern. The state is a square on a fixed board, and the moves never change, so the neighbours come from 8 fixed offsets. The next problems keep the same BFS but change what a state is: a four-digit lock code, a word, or a square with snakes and ladders.

10

Don't make this mistake

Greedy: always step to the square closest to the target
✗ choose the move that minimises |row − targetRow| + |col − targetCol|, then repeat
✓ try all 8 moves from every square with BFS

Closest on the board is not the same as fewest moves. On an 8 × 8 board, from (1,1) toward (2,2): the knight can jump to (3,2), which is one step away by distance. From (3,2) the closest moves are (1,1), (1,3) and (2,4), all two steps away. From (1,3) the closest moves are (3,2) and (2,1). If ties go to the first move in the code's move list, the walk goes (1,1) → (3,2) → (1,3) → (3,2) → … and never reaches (2,2). The real answer is 4.

Using DFS, which finds a route but not the shortest one
✗ use a stack and return the depth the first time the target is popped
✓ use a queue, so squares are reached in order of distance

DFS goes deep down one route before it tries the others, so the first route it finds can be long. On this 5 × 5 board from (1,1) to (3,3), a DFS with a visited set (trying moves in the order used in this walkthrough) finds (1,1) → (3,2) → (5,3) → (3,4) → (5,5) → (4,3) → (2,4) → (4,5) → (3,3) first. That is 8 moves, while BFS finds one with 4.

Forgetting the statement is 1-indexed
✗ int r = knightPos[0], c = knightPos[1];
✓ int r = knightPos[0] - 1, c = knightPos[1] - 1;

The top-left square is (1, 1), but C++ arrays start at index 0. Without the −1, a knight on (8, 8) on an 8 × 8 board would use index 8, one past the last row, and the dist table would be read or written outside its bounds.

11

Want to implement this?

Write it yourself on GeeksforGeeks, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.