How to find the minimum number of steps needed by knight to reach the destination using C#?

In chess, a knight moves in an L-shape − two squares in one direction and one square perpendicular to that. This article explains how to find the minimum number of steps (moves) needed for a knight to reach a destination cell on a chessboard using Breadth-First Search (BFS) algorithm in C#.

The knight's movement pattern creates a shortest path problem that can be efficiently solved using BFS, as it explores all possible moves level by level, guaranteeing the minimum number of steps.

Knight's Movement Pattern

A knight can move to at most 8 positions from any given cell. The movement offsets are −

Knight's Possible Moves K (-2,-1) (-1,-2) (1,-2) (2,-1) 8 possible L-shaped moves

Algorithm Approach

The solution uses BFS (Breadth-First Search) because −

  • BFS explores all positions reachable in k moves before exploring positions reachable in k+1 moves

  • This guarantees that the first time we reach the target, it's via the shortest path

  • Each cell is visited only once, avoiding infinite loops

Example

using System;
using System.Collections.Generic;

public class KnightWalkProblem {
    public class Cell {
        public int x, y;
        public int distance;
        
        public Cell(int x, int y, int distance) {
            this.x = x;
            this.y = y;
            this.distance = distance;
        }
    }
    
    static bool IsInside(int x, int y, int N) {
        return (x >= 1 && x <= N && y >= 1 && y <= N);
    }
    
    public int MinStepToReachTarget(int[] knightPos, int[] targetPos, int N) {
        // Knight's 8 possible moves (dx, dy)
        int[] dx = { -2, -1, 1, 2, -2, -1, 1, 2 };
        int[] dy = { -1, -2, -2, -1, 1, 2, 2, 1 };
        
        Queue<Cell> queue = new Queue<Cell>();
        queue.Enqueue(new Cell(knightPos[0], knightPos[1], 0));
        
        bool[,] visited = new bool[N + 1, N + 1];
        visited[knightPos[0], knightPos[1]] = true;
        
        while (queue.Count != 0) {
            Cell current = queue.Dequeue();
            
            // If we reached the target
            if (current.x == targetPos[0] && current.y == targetPos[1])
                return current.distance;
            
            // Try all 8 possible knight moves
            for (int i = 0; i < 8; i++) {
                int newX = current.x + dx[i];
                int newY = current.y + dy[i];
                
                if (IsInside(newX, newY, N) && !visited[newX, newY]) {
                    visited[newX, newY] = true;
                    queue.Enqueue(new Cell(newX, newY, current.distance + 1));
                }
            }
        }
        
        return -1; // Target unreachable
    }
}

class Program {
    static void Main(string[] args) {
        KnightWalkProblem knight = new KnightWalkProblem();
        int N = 8; // 8x8 chessboard
        int[] knightPos = { 1, 1 }; // Starting position
        int[] targetPos = { 8, 8 }; // Target position
        
        int steps = knight.MinStepToReachTarget(knightPos, targetPos, N);
        Console.WriteLine("Minimum steps needed: " + steps);
        
        // Test with different positions
        int[] pos2 = { 1, 1 };
        int[] target2 = { 3, 3 };
        int steps2 = knight.MinStepToReachTarget(pos2, target2, N);
        Console.WriteLine("Steps from (1,1) to (3,3): " + steps2);
    }
}

The output of the above code is −

Minimum steps needed: 6
Steps from (1,1) to (3,3): 2

How It Works

  1. Initialize: Start BFS from knight's initial position with distance 0

  2. Explore: For each position, try all 8 possible knight moves

  3. Check bounds: Ensure the new position is within the chessboard

  4. Track visited: Mark visited cells to avoid cycles

  5. Return: When target is reached, return the distance

Time and Space Complexity

Aspect Complexity Explanation
Time Complexity O(N²) Each cell is visited at most once
Space Complexity O(N²) For the visited array and queue storage

Conclusion

The knight's minimum step problem is efficiently solved using BFS, which guarantees the shortest path by exploring all positions level by level. The algorithm handles the knight's unique L-shaped movement pattern and ensures each cell is visited only once for optimal performance.

Updated on: 2026-03-17T07:04:36+05:30

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements