Minimum Step by Knight

Pattern: Grid graphs

hard

A knight's moves are the edges of a graph whose vertices are the squares. BFS from the knight's square gives the fewest moves to every square; stop when the target is reached.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

On an n × n board (squares numbered from 1), return the fewest knight moves from knightPos to targetPos, or -1 if it cannot be reached.

Think first

  • How many moves does a knight have from one square?
  • Is every move the same cost?
  • When is a target unreachable?

Hints

    Brute force, and why it fails

    DFS trying every route with a depth limit: exponential.

    The key insight

    BFS over squares finds the fewest moves, visiting each square once.

    Dry run

    moves1

    n = 6, knight at (4, 5), target (1, 1). Moves from (4, 5): (2, 4), (3, 3), (5, 3), (6, 4), ...

    Step 1 of 3

    The plan

    BFS from the start over the 8 knight moves inside the board; return the target's distance
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Each square is visited at most once.

    Edge cases

    • Start equals target: 0.
    • A 2 × 2 board: -1.
    • Opposite corners of a large board.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int minStepToReachTarget(int[] knightPos, int[] targetPos, int n) {
            int[][] moves = {{1, 2}, {2, 1}, {-1, 2}, {-2, 1}, {1, -2}, {2, -1}, {-1, -2}, {-2, -1}};
            int[][] dist = new int[n + 1][n + 1];   // squares are numbered 1..n
            for (int[] row : dist) Arrays.fill(row, -1);
            Queue<int[]> q = new ArrayDeque<>();
            q.add(knightPos);
            dist[knightPos[0]][knightPos[1]] = 0;
            while (!q.isEmpty()) {                  // each move is one step: BFS gives the fewest
                int[] u = q.poll();
                if (u[0] == targetPos[0] && u[1] == targetPos[1]) return dist[u[0]][u[1]];
                for (int[] m : moves) {
                    int r = u[0] + m[0], c = u[1] + m[1];
                    if (r >= 1 && c >= 1 && r <= n && c <= n && dist[r][c] == -1) {
                        dist[r][c] = dist[u[0]][u[1]] + 1;
                        q.add(new int[]{r, c});
                    }
                }
            }
            return -1;
        }
    }

    C++

    class Solution {
    public:
        int minStepToReachTarget(vector<int>& knightPos, vector<int>& targetPos, int n) {
            int mr[8] = {1, 2, -1, -2, 1, 2, -1, -2}, mc[8] = {2, 1, 2, 1, -2, -1, -2, -1};
            vector<vector<int>> dist(n + 1, vector<int>(n + 1, -1));   // squares are numbered 1..n
            queue<pair<int, int>> q;
            q.push(make_pair(knightPos[0], knightPos[1]));
            dist[knightPos[0]][knightPos[1]] = 0;
            while (!q.empty()) {                    // each move is one step: BFS gives the fewest
                pair<int, int> u = q.front();
                q.pop();
                if (u.first == targetPos[0] && u.second == targetPos[1]) return dist[u.first][u.second];
                for (int k = 0; k < 8; k++) {
                    int r = u.first + mr[k], c = u.second + mc[k];
                    if (r >= 1 && c >= 1 && r <= n && c <= n && dist[r][c] == -1) {
                        dist[r][c] = dist[u.first][u.second] + 1;
                        q.push(make_pair(r, c));
                    }
                }
            }
            return -1;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def minStepToReachTarget(self, knightPos: list[int], targetPos: list[int], n: int) -> int:
            moves = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]
            start, goal = tuple(knightPos), tuple(targetPos)
            dist = {start: 0}                       # squares are numbered 1..n
            q = deque([start])
            while q:                                # each move is one step: BFS gives the fewest
                r, c = q.popleft()
                if (r, c) == goal:
                    return dist[(r, c)]
                for a, b in moves:
                    nxt = (r + a, c + b)
                    if 1 <= nxt[0] <= n and 1 <= nxt[1] <= n and nxt not in dist:
                        dist[nxt] = dist[(r, c)] + 1
                        q.append(nxt)
            return -1

    Common mistakes

    • Using 0-based checks with 1-based squares.
    • Missing some of the 8 moves.

    Similar problems