Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.
Examples:
Input:
Knight
knightPosition: (1, 3) , targetPosition: (5, 0)
Output: 3 Explanation: In above diagram Knight takes 3 step to reach from (1, 3) to (5, 0) (1, 3) -> (3, 4) -> (4, 2) -> (5, 0)
Start with the knight's initial position and mark it as visited.
Initialize a queue for BFS, where each entry stores the knight's current position and the distance from the starting position.
Explore all 8 possible moves a knight can make from its current position.
For each move:
Check if the new position is within the board boundaries.
Check if the position has not been visited yet.
If valid, push this new position into the queue with a distance 1 more than its parent.
During BFS, if the current position is the target position, return the distance of that position.
Repeat until the target is found or all possible positions are explored.
C++
#include<bits/stdc++.h>usingnamespacestd;// structure for storing a cell's datastructcell{intx,y,dis;cell():x(0),y(0),dis(0){}cell(intx,inty,intdis):x(x),y(y),dis(dis){}};// Utility method to check if (x, y) is inside the boardboolisInside(intx,inty,intn){returnx>=1&&x<=n&&y>=1&&y<=n;}// Method to return the minimum steps to reach targetintminSteps(intknightPos[],inttargetPos[],intn){// x and y direction where a knight can moveintdx[]={-2,-1,1,2,-2,-1,1,2};intdy[]={-1,-2,-2,-1,1,2,2,1};// queue for storing knight's statesqueue<cell>q;// push starting position of knight with 0 distanceq.push(cell(knightPos[0],knightPos[1],0));cellt;intx,y;// Visit array initialized to falsevector<vector<bool>>visit(n+1,vector<bool>(n+1,false));// visit starting positionvisit[knightPos[0]][knightPos[1]]=true;// loop until queue is emptywhile(!q.empty()){t=q.front();q.pop();// if target is reached, return the distanceif(t.x==targetPos[0]&&t.y==targetPos[1])returnt.dis;// explore all reachable positionsfor(inti=0;i<8;i++){x=t.x+dx[i];y=t.y+dy[i];// if the position is valid and not visited, push it to queueif(isInside(x,y,n)&&!visit[x][y]){visit[x][y]=true;q.push(cell(x,y,t.dis+1));}}}// if no path found, return -1return-1;}intmain(){intn=30;intknightPos[]={1,1};inttargetPos[]={30,30};cout<<minSteps(knightPos,targetPos,n);return0;}
Java
importjava.util.*;// Class to store the cell's dataclassCell{intx,y,dis;// Default constructorCell(){this.x=0;this.y=0;this.dis=0;}// Parameterized constructorCell(intx,inty,intdis){this.x=x;this.y=y;this.dis=dis;}}publicclassSolution{// Utility method to check if (x, y) is inside the boardstaticbooleanisInside(intx,inty,intn){returnx>=1&&x<=n&&y>=1&&y<=n;}// Method to return the minimum steps to reach targetstaticintminSteps(int[]knightPos,int[]targetPos,intn){// x and y direction where a knight can moveint[]dx={-2,-1,1,2,-2,-1,1,2};int[]dy={-1,-2,-2,-1,1,2,2,1};// Queue for storing knight's statesQueue<Cell>q=newLinkedList<>();// Push starting position of knight with 0 distanceq.add(newCell(knightPos[0],knightPos[1],0));Cellt;intx,y;// Visit array initialized to falseboolean[][]visit=newboolean[n+1][n+1];// Visit starting positionvisit[knightPos[0]][knightPos[1]]=true;// Loop until queue is emptywhile(!q.isEmpty()){t=q.poll();// If target is reached, return the distanceif(t.x==targetPos[0]&&t.y==targetPos[1])returnt.dis;// Explore all reachable positionsfor(inti=0;i<8;i++){x=t.x+dx[i];y=t.y+dy[i];// If the position is valid and not visited, // push it to the queueif(isInside(x,y,n)&&!visit[x][y]){visit[x][y]=true;q.add(newCell(x,y,t.dis+1));}}}// If no path found, return -1return-1;}// Driver codepublicstaticvoidmain(String[]args){intn=30;int[]knightPos={1,1};int[]targetPos={30,30};System.out.println(minSteps(knightPos,targetPos,n));}}
Python
# structure for storing a cell's dataclassCell:def__init__(self,x=0,y=0,dis=0):self.x=xself.y=yself.dis=dis# Utility method to check if (x, y) is inside the boarddefisInside(x,y,n):return1<=x<=nand1<=y<=n# Method to return the minimum steps to reach targetdefminSteps(knightPos,targetPos,n):# x and y direction where a knight can movedx=[-2,-1,1,2,-2,-1,1,2]dy=[-1,-2,-2,-1,1,2,2,1]# queue for storing knight's statesq=[]# push starting position of knight with 0 distanceq.append(Cell(knightPos[0],knightPos[1],0))visit=[[False]*(n+1)for_inrange(n+1)]# visit starting positionvisit[knightPos[0]][knightPos[1]]=True# loop until queue is emptywhileq:t=q.pop(0)# if target is reached, return the distanceift.x==targetPos[0]andt.y==targetPos[1]:returnt.dis# explore all reachable positionsforiinrange(8):x=t.x+dx[i]y=t.y+dy[i]# if the position is valid and not visited, push it to queueifisInside(x,y,n)andnotvisit[x][y]:visit[x][y]=Trueq.append(Cell(x,y,t.dis+1))# if no path found, return -1return-1# Driver codeif__name__=='__main__':n=30knightPos=[1,1]targetPos=[30,30]print(minSteps(knightPos,targetPos,n))
C#
usingSystem;usingSystem.Collections.Generic;// Class to store a cell's dataclassCell{publicintx,y,dis;publicCell(){x=0;y=0;dis=0;}// Default constructorpublicCell(intx,inty,intdis){this.x=x;this.y=y;this.dis=dis;}}classSolution{// Utility method to check if (x, y) is inside the boardstaticboolIsInside(intx,inty,intn){returnx>=1&&x<=n&&y>=1&&y<=n;}// Method to return the minimum steps to reach targetstaticintMinSteps(int[]knightPos,int[]targetPos,intn){// x and y directions where a knight can moveint[]dx={-2,-1,1,2,-2,-1,1,2};int[]dy={-1,-2,-2,-1,1,2,2,1};// Queue for storing knight's statesQueue<Cell>q=newQueue<Cell>();// Push starting position of knight with 0 distanceq.Enqueue(newCell(knightPos[0],knightPos[1],0));Cellt;intx,y;// Visit array initialized to falsebool[,]visit=newbool[n+1,n+1];// Visit starting positionvisit[knightPos[0],knightPos[1]]=true;// Loop until queue is emptywhile(q.Count>0){t=q.Dequeue();// If target is reached, return the distanceif(t.x==targetPos[0]&&t.y==targetPos[1])returnt.dis;// Explore all reachable positionsfor(inti=0;i<8;i++){x=t.x+dx[i];y=t.y+dy[i];// If the position is valid and not visited, push it to queueif(IsInside(x,y,n)&&!visit[x,y]){visit[x,y]=true;q.Enqueue(newCell(x,y,t.dis+1));}}}// If no path found, return -1return-1;}// Driver codestaticvoidMain(){intn=30;int[]knightPos={1,1};int[]targetPos={30,30};Console.WriteLine(MinSteps(knightPos,targetPos,n));}}
JavaScript
// structure for storing a cell's dataclassCell{constructor(x,y,dis){this.x=x;this.y=y;this.dis=dis;}}// Utility method to check if (x, y) is inside the boardfunctionisInside(x,y,n){returnx>=1&&x<=n&&y>=1&&y<=n;}// Method to return the minimum steps to reach targetfunctionminSteps(knightPos,targetPos,n){// x and y direction where a knight can moveconstdx=[-2,-1,1,2,-2,-1,1,2];constdy=[-1,-2,-2,-1,1,2,2,1];// queue for storing knight's statesconstq=[];// push starting position of knight with 0 distanceq.push(newCell(knightPos[0],knightPos[1],0));lett;letx,y;// Visit array initialized to falseconstvisit=Array.from({length:n+1},()=>Array(n+1).fill(false));// visit starting positionvisit[knightPos[0]][knightPos[1]]=true;// loop until queue is emptywhile(q.length>0){t=q.shift();// if target is reached, return the distanceif(t.x===targetPos[0]&&t.y===targetPos[1])returnt.dis;// explore all reachable positionsfor(leti=0;i<8;i++){x=t.x+dx[i];y=t.y+dy[i];// if the position is valid and not visited, push it to queueif(isInside(x,y,n)&&!visit[x][y]){visit[x][y]=true;q.push(newCell(x,y,t.dis+1));}}}// if no path found, return -1return-1;}// Driver codeconstn=30;constknightPos=[1,1];consttargetPos=[30,30];console.log(minSteps(knightPos,targetPos,n));