Steps by Knight | Practice Medium 0 attempts
GeeksforGeeks ↗

Steps by Knight | Practice

Medium GraphBFSDFS GeeksforGeeks

Given an N×N chessboard, find the minimum steps a knight takes from source to destination.

Example: N=6, source=(4,5), target=(1,1) → Output: 3

Sample Input
Sample Output
Constraints
  • 1 <= N <= 1000
Topics

BFS

function minSteps(n, src, dest) {
  const moves = [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]];
  const visited = Array.from({length:n}, ()=>Array(n).fill(false));
  const q = [[src[0],src[1],0]]; visited[src[0]][src[1]] = true;
  while (q.length) {
    const [r,c,d] = q.shift();
    if (r===dest[0] && c===dest[1]) return d;
    for (const [dr,dc] of moves) {
      const nr=r+dr, nc=c+dc;
      if (nr>=0&&nr<n&&nc>=0&&nc<n&&!visited[nr][nc]) { visited[nr][nc]=true; q.push([nr,nc,d+1]); }
    }
  }
  return -1;
}

Time: O(n²) | Space: O(n²)

Saved in this browser only. Private to you.

JavaScript