Steps by Knight

Given a square chessboard, the initial position of Knight and position of a target. Find out the minimum steps a Knight will take to reach the target position.

Note: index are zero-based.

class Solution
{
    // There is only 8 possible way that a Knight can move within the chessboard. 
    private (int, int)[] directions = [(-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1)];
    // Function to find out minimum steps Knight needs to reach target position.
    public int MinStepToReachTarget(List<int> KnightPos, List<int> TargetPos, int N)
    {
        bool[,] visited = new bool[N, N];
        Queue<(int, int, int)> queue = new Queue<(int, int, int)>();
        queue.Enqueue((KnightPos[0], KnightPos[1], 0));

        while (queue.Count > 0)
        {
            var (x, y, dis) = queue.Dequeue();
            if (x == TargetPos[0] && y == TargetPos[1])
            {
                return dis;
            }

            foreach ((int xP, int yP) in directions)
            {
                // move next step
                int newX = x + xP;
                int newY = y + yP;

                if (newX >= 0 && newX <= N && newY >= 0 && newY <= N && !visited[newX, newY])
                {
                    visited[newX, newY] = true;
                    queue.Enqueue((newX, newY, dis + 1));
                }
            }
        }

        return -1;
    }
}

Last updated