Steps by Knight | Practice | GeeksforGeeks

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:
The initial and the target position coordinates of Knight have been given according to 1-base indexing.
 
Example 1:
Input:
N=6
knightPos[ ] = {4, 5}
targetPos[ ] = {1, 1}
Output:
3
Explanation:

Knight takes 3 step to reach from 
(4, 5) to (1, 1):
(4, 5) -> (5, 3) -> (3, 2) -> (1, 1).
 
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function minStepToReachTarget() which takes the initial position of Knight (KnightPos), the target position of Knight (TargetPos), and the size of the chessboard (N) as input parameters and returns the minimum number of steps required by the knight to reach from its current position to the given target position.
 
Expected Time Complexity: O(N2).
Expected Auxiliary Space: O(N2).
 
Constraints:
1 <= N <= 1000
1 <= Knight_pos(X, Y), Targer_pos(X, Y) <= N
0
neeshumaini553 days ago
def __init__(self, x = 0, y = 0, dist = 0): self.x = x self.y = y self.dist = dist # checks whether given position is# inside the board   def isInside(self,x, y, N):    if (x >= 1 and x <= N and     y >= 1 and y <= N):     return True    return False# Method returns minimum step to reach# target position   def minStepToReachTarget(self,knightpos,     targetpos, N):# all possible movements for the knight    dx = [2, 2, -2, -2, 1, 1, -1, -1]    dy = [1, -1, 1, -1, 2, -2, 2, -2]    queue = []# push starting position of knight# with 0 distance    queue.append(Solution(knightpos[0], knightpos[1], 0))# make all cell unvisited    visited = [[False for i in range(N + 1)]    for j in range(N + 1)]# visit starting state    visited[knightpos[0]][knightpos[1]] = True# loop until we have one element in queue    while(len(queue) > 0):      t = queue[0]     queue.pop(0)  # if current cell is equal to target # cell, return its distance     if(t.x == targetpos[0] and     t.y == targetpos[1]):      return t.dist   # iterate for all reachable states     for i in range(8):        x = t.x + dx[i]      y = t.y + dy[i]        if(self.isInside(x, y, N) and not visited[x][y]):       visited[x][y] = True       queue.append(Solution(x, y, t.dist + 1))
     
0
ishanpatni4 days ago
Java
.22s
 class Solution{   class Pair{       int x,y;       Pair(int x,int y){           this.x=x;           this.y=y;       }   }   //Function to find out minimum steps Knight needs to reach target position.   public int minStepToReachTarget(int KnightPos[], int TargetPos[], int n)   {       int ans=0;       int board[][]=new int[n][n];       int tx=TargetPos[0]-1;       int ty=TargetPos[1]-1;          int sx=KnightPos[0]-1;       int sy=KnightPos[1]-1;       boolean vis[][]=new boolean[n][n];       // int distance[][]=new int[n][n];       int dx[]={-2,-2,-1,-1,1,1,2,2};       int dy[]={-1,1,-2,2,-2,2,-1,1};              Queue<Pair>q=new LinkedList<>();       q.add(new Pair(sx,sy));       // distance[sx][sy]=0;       int level=0;       for(int i=0;i<n;i++){           for(int j=0;j<n;j++){               vis[i][j]=false;                          }       }       vis[sx][sy]=true;       while(!q.isEmpty()){       int size=q.size();       while(size-->0){       Pair node=q.poll();       int currx=node.x;       int curry=node.y;              for(int i=0;i<8;i++){           int nx=currx+dx[i];           int ny=curry+dy[i];                       if(nx==tx&&ny==ty){                   return level+1;               }                      if(nx>=0&&nx<n&&ny>=0&&ny<n&&vis[nx][ny]==false){               vis[nx][ny]=true;               // distance[nx][ny]=distance[currx][curry]+1;                             q.add(new Pair(nx,ny));                          }       }                  }       level++;                  }       return 0;   }   }
0
tashu6285 days ago
can anyone tell me what is wrong with this code
public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N){    int time = 0;    Queue<Position> q = new LinkedList<Position>();    Position p = new Position(KnightPos[0],KnightPos[1]);    q.add(p);    boolean matrix[][] = new boolean[N][N];    matrix[KnightPos[0]][KnightPos[1]] = true;    while (q.isEmpty()){        int size = q.size();        int r_place = q.poll().x;        int c_place = q.poll().y;        time++;        for (int i = 0; i < size; i++) {            /** right **/            if (c_place+2 < matrix[0].length){                /** right - up **/                if (r_place-1 >= 0 && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }                /** right - Down **/                if (r_place+1 < matrix.length && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }            }            /** left **/            if (c_place-2 >= 0){                /** left - up **/                if (r_place-1 >= 0 && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }                /** right - Down **/                if (r_place+1 < matrix.length && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }            }            /** up **/            if (r_place-2 >= 0){                /** up - left **/                if (c_place-1 >= 0 && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }                /** right - Down **/                if (c_place+1 < matrix[0].length && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }            }            /** Down **/            if (r_place+2 < matrix[0].length){                /** up - left **/                if (c_place-1 >= 0 && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }                /** right - Down **/                if (c_place+1 < matrix[0].length && matrix[r_place][c_place] == false){                    matrix[r_place][c_place] = true;                    q.add(new Position(r_place , c_place));                }            }            if (r_place == TargetPos[0] && c_place == TargetPos[1]){                break;            }        }        q.poll();    }    return time;}
static class Position {    int x;    int y;    Position(int x, int y) {        this.x = x;        this.y = y;    }}
 
0
jainmuskan5651 week ago
	int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N)
	{
	    int x1= KnightPos[0];
	    int x2= TargetPos[0];
	    int y1= KnightPos[1];
	    int y2= TargetPos[1];
	    
	    if(x1==x2 && y1==y2){
	        return 0; // already at the destination case
	    }
	    queue<pair<int,int>>q; // stores the position to visit next
	    q.push({x1-1,y1-1});
	    vector<vector<int>> visited(N,vector<int>(N,0)); // stores the visited or not visited
	    visited[x1-1][y1-1]=0;
	    while(!q.empty()){
	        auto curr= q.front();
	        q.pop();
	        int i= curr.first;
	        int j= curr.second;
	        if(i-2>=0 && j-1>=0 && i-2<N && j-1<N && visited[i-2][j-1]==0){
	            visited[i-2][j-1]= 1+visited[i][j];
	            q.push({i-2,j-1});
	        }
	        if(i-2>=0 && j+1>=0 && i-2<N && j+1<N && visited[i-2][j+1]==0){
	            visited[i-2][j+1]= 1+visited[i][j];
	            q.push({i-2,j+1});
	        }
	        if(i-1>=0 && j+2>=0 && i-1<N && j+2<N && visited[i-1][j+2]==0){
	            visited[i-1][j+2]= 1+visited[i][j];
	            q.push({i-1,j+2});
	        }
	        if(i+1>=0 && j+2>=0 && i+1<N && j+2<N && visited[i+1][j+2]==0){
	            visited[i+1][j+2]= 1+visited[i][j];
	            q.push({i+1,j+2});
	        }
	        
	        if(i+2>=0 && j-1>=0 && i+2<N && j-1<N && visited[i+2][j-1]==0){
	            visited[i+2][j-1]= 1+visited[i][j];
	            q.push({i+2,j-1});
	        }
	        if(i+2>=0 && j+1>=0 && i+2<N && j+1<N && visited[i+2][j+1]==0){
	            visited[i+2][j+1]= 1+visited[i][j];
	            q.push({i+2,j+1});
	        }
	        if(i-1>=0 && j-2>=0 && i-1<N && j-2<N && visited[i-1][j-2]==0){
	            visited[i-1][j-2]= 1+visited[i][j];
	            q.push({i-1,j-2});
	        }
	        if(i+1>=0 && j-2>=0 && i+1<N && j-2<N && visited[i+1][j-2]==0){
	            visited[i+1][j-2]= 1+visited[i][j];
	            q.push({i+1,j-2});
	        }
	    }
	    return visited[x2-1][y2-1];
	}
0
ashuthe11 week ago
Simple C++ Solution using bfs , Time 0.014 sec
By Ashutosh Gautam
 #define INF 1e9+10      int level[1010][1010];   int vis[1010][1010];      vector<pair<int,int>> movements = {       {1,2},{-1,2},{1,-2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}   };      bool isVal(int x , int y, int n){       if(x >= 1 && x <= n && y >= 1 && y <= n) return true;       return false;   }      int bfs(vector<int>&KnightPos,vector<int>&TargetPos,int N)   {       queue<pair<int,int>>q;       q.push({KnightPos[0],KnightPos[1]});              level[KnightPos[0]][KnightPos[1]] = 0;              while(!q.empty()){           auto p = q.front();           int x = p.first, y = p.second;           q.pop();                      for(auto movement : movements){               int childX = x + movement.first;               int childY = y + movement.second;                              if(!isVal(childX,childY,N)) continue;                              if(!vis[childX][childY]){                   q.push({childX,childY});                   vis[childX][childY] = 1;                   level[childX][childY] = level[x][y]+1;               }           }       }              return level[TargetPos[0]][TargetPos[1]];   }   int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N){    memset(vis,0,sizeof(vis));    memset(level,INF,sizeof(level));    return bfs(KnightPos,TargetPos,N);}
0
ashutoshrastogi3 weeks ago
C++ Easy BFS Code
 
int minStepToReachTarget(vector<int>&kni,vector<int>&tar,int n)
	{
	    int mat[n+1][n+1] = {0};
	    pair<int, int> p;
	    queue<pair<int, int> > q; 
	    
	    q.push({kni[0], kni[1]});
	    int sum = 0;
	    mat[kni[0]][kni[1]] = 0;
	    
	    while(!q.empty()){
	        
	        p = q.front();
	        q.pop();
	        int a = p.first;
	        int b = p.second;
	        sum = mat[a][b]+1;
	        
	        if(a==tar[0] && tar[1]==b)
	            break;
	        if(a+1<=n && b-2>0 && mat[a+1][b-2]==0){
	            q.push({a+1, b-2});
	            mat[a+1][b-2] = sum;
	        }
	        if(a-1>0 && b-2>0 && mat[a-1][b-2]==0){
	            q.push({a-1, b-2});
	            mat[a-1][b-2] = sum;
	        }
	        
	        if(a+1<=n && b+2<=n && mat[a+1][b+2]==0){
	            q.push({a+1, b+2});
	            mat[a+1][b+2] = sum;
	        }
	        if(a-1>0 && b+2<=n && mat[a-1][b+2]==0){
	            q.push({a-1, b+2});
	            mat[a-1][b+2] = sum;
	        }
	        
	        
	        if(a-2>0 && b-1>0 && mat[a-2][b-1]==0){
	            q.push({a-2, b-1});
	            mat[a-2][b-1] = sum;
	        }
	        if(a-2>0 && b+1<=n && mat[a-2][b+1]==0){
	            q.push({a-2, b+1});
	            mat[a-2][b+1] = sum;
	        }
	        if(a+2<=n && b-1>0 && mat[a+2][b-1]==0){
	            q.push({a+2, b-1});
	            mat[a+2][b-1] = sum;
	        }
	        if(a+2<=n && b+1<=n && mat[a+2][b+1]==0){
	            q.push({a+2, b+1});
	            mat[a+2][b+1] = sum;
	        }
	    }
	    
	    return sum-1;
	    
	}
0
vardhanjaingfg3 weeks ago
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
class Solution 
{
    public:
    //Function to find out minimum steps Knight needs to reach target position.
	int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int n)
	{
	    int x1=KnightPos[0];
	    int y1=KnightPos[1];
	    
	    int x2=TargetPos[0];
	    int y2=TargetPos[1];
	    
	    int arr[1001][1001];
	    for(int i=0;i<n;i++)
	    {
	        for(int j=0;j<n;j++)
	        {
	            arr[i][j]=0;
	        }
	    }
	    if(x1==x2&&y1==y2) return 0;
	    queue<pair<int,int>> q;
	    q.push({x1-1,y1-1});
	    while(q.empty()==false)
	    {
	        auto curr=q.front();
	        int i=curr.first;
	        int j=curr.second;
	        q.pop();
	        
	        if((i+1)<n&&(i+1)>=0&&(j+2)<n&&(j+2)>=0&&arr[i+1][j+2]==0)
	        {
	            arr[i+1][j+2]=arr[i][j]+1;
	            q.push(make_pair(i+1,j+2));
	        }
	         if((i-1)>=0&&(j+2)<n&&(i-1)<n&&(j+2)>=0&&arr[i-1][j+2]==0)
	        {
	            arr[i-1][j+2]=arr[i][j]+1;
	            q.push(make_pair(i-1,j+2));
	        }
	        if((i-2)>=0&&(j+1)<n&&(i-2)<n&&(j+1)>=0&&arr[i-2][j+1]==0)
	        {
	            arr[i-2][j+1]=arr[i][j]+1;
	            q.push(make_pair(i-2,j+1));
	        }
	         if((i+2)<n&&(j+1)<n&&(i+2)>=0&&(j+1)>=0&&arr[i+2][j+1]==0)
	        {
	            arr[i+2][j+1]=arr[i][j]+1;
	            q.push(make_pair(i+2,j+1));
	        }
	          if((i-1)>=0&&(j-2)>=0&&(i-1)<n&&(j-2)<n&&arr[i-1][j-2]==0)
	        {
	            arr[i-1][j-2]=arr[i][j]+1;
	            q.push(make_pair(i-1,j-2));
	        }
	        if((i+1)<n&&(j-2)>=0&&(i+1)>=0&&(j-2)<n&&arr[i+1][j-2]==0)
	        {
	            arr[i+1][j-2]=arr[i][j]+1;
	            q.push(make_pair(i+1,j-2));
	        }
	       
	        if((i+2)<n&&(j-1)>=0&&(i+2)>=0&&(j-1)<n&&arr[i+2][j-1]==0)
	        {
	            arr[i+2][j-1]=arr[i][j]+1;
	            q.push(make_pair(i+2,j-1));
	        }
	       
	      
	        if((i-2)>=0&&(j-1)>=0&&(i-2)<n&&(j-1)<n&&arr[i-2][j-1]==0)
	        {
	            arr[i-2][j-1]=arr[i][j]+1;
	            q.push(make_pair(i-2,j-1));
	        }
	        
	    }
	    return arr[x2-1][y2-1];
	}
};

// { Driver Code Starts.
int main(){
	int tc;
	cin >> tc;
	while(tc--){
		vector<int>KnightPos(2);
		vector<int>TargetPos(2);
		int N;
		cin >> N;
		cin >> KnightPos[0] >> KnightPos[1];
		cin >> TargetPos[0] >> TargetPos[1];
		Solution obj;
		int ans = obj.minStepToReachTarget(KnightPos, TargetPos, N);
		cout << ans <<"\n";
	}
	return 0;
}  // } Driver Code Ends
+1
saurabhsathe12341 month ago
C++ : 0.1 ms
 
Used level wise BFS , as we need minimum steps or level to find target.
 
bool check(int i,int j,int N)
    {
        if(i<0 || j<0 || i>=N || j>=N)
            return false;
            
        return true;
    }
	int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N)
	{
	    // Code here
	    vector<vector<bool>> visited (N,vector<bool>(N,false));
	    pair<int,int> start = { KnightPos[0] -1 ,KnightPos[1] - 1};
	    pair<int,int> end = { TargetPos[0] - 1,TargetPos[1] - 1};
	    
	    queue<pair<int,int>> q;
	    q.push(start);
	    visited[start.first][start.second] = true;
	    
	    int level = 0 ;
	    
	    vector<pair<int,int>> cord = { {-1,2} , {1,2} , {-1,-2} , {1,-2} ,
	                                   {2,1} ,{2,-1} , {-2,-1} , {-2 , 1} };
	    
	    while(!q.empty())
	    {
	        int size = q.size();
	        for(int c=0;c<size;c++)
	        {
	            
	            int i = q.front().first;
	            int j = q.front().second;
	            
	            if(q.front() == end)
	                return level;
	                
	           for(int k=0 ; k<8 ; k++)
	           {
	               int x = cord[k].first;
	               int y = cord[k].second;
	               
	                if(check(i+x,j+y,N) && !visited[i+x][j+y])
    	            {
    	                q.push({i+x,j+y});
    	                visited[i+x][j+y] = true;
    	            }
	               
	           }
	            
	           // if(check(i-1,j+2,N) && !visited[i-1][j+2])
	           // {
	           //     q.push({i-1,j+2});
	           //     visited[i-1][j+2] = true;
	           // }
	           // if(check(i+1,j+2,N) && !visited[i+1][j+2])
	           // {
	           //     q.push({i+1,j+2});
	           //     visited[i+1][j+2] = true;
	           // }
	           // if(check(i+1,j-2,N) && !visited[i+1][j-2])
	           // {
	           //     q.push({i+1,j-2});
	           //     visited[i+1][j-2] = true;
	           // }
	           // if(check(i-1,j-2,N) && !visited[i-1][j-2])
	           // {
	           //     q.push({i-1,j-2});
	           //     visited[i-1][j-2] = true;
	           // }
	           // if(check(i+2,j+1,N) && !visited[i+2][j+1])
	           // {
	           //     q.push({i+2,j+1});
	           //     visited[i+2][j+1] = true;
	           // }
	           // if(check(i+2,j-1,N) && !visited[i+2][j-1])
	           // {
	           //     q.push({i+2,j-1});
	           //     visited[i+2][j-1] = true;
	           // }
	           // if(check(i-2,j+1,N) && !visited[i-2][j+1])
	           // {
	           //     q.push({i-2,j+1});
	           //     visited[i-2][j+1] = true;
	           // }
	           // if(check(i-2,j-1,N) && !visited[i-2][j-1])
	           // {
	           //     q.push({i-2,j-1});
	           //     visited[i-2][j-1] = true;
	           // }
	            
	            q.pop();
	        }
	        level++;
	    }
	    
	    return -1;
	    
	}
+1
unknownladyme1 month ago
Can someone tell me why my DFS code didn't work?
class Solution 
{  
    public:
    
    int ans = INT_MAX;
    void fun(int i ,int j, vector<int> tp, int n , int count, vector<vector<bool> > visited)
    {
        if(i<1||i>n||j<1||j>n )return;
        if(visited[i][j])return;
        visited[i][j] = 1;
        count++;
        if(i == tp[0] && j == tp[1])
        {
            ans = min(ans,count);return;
        }
     
         fun(i-1,j-2,tp,n ,count,visited);
         fun(i+1,j-2,tp,n ,count,visited);
         fun(i-2,j-1,tp,n ,count,visited);
         fun(i-2,j+1,tp,n ,count,visited);
         fun(i-1,j+2,tp,n ,count,visited);
         fun(i+1,j+2,tp,n ,count,visited);
         fun(i+2,j+1,tp,n ,count,visited);
         fun(i+2,j-1,tp,n ,count,visited);
        
    }
    //Function to find out minimum steps Knight needs to reach target position.
	int minStepToReachTarget(vector<int>&kp,vector<int>&tp,int n)
	{
	    // Code here
	    vector<vector<bool> > visited(n+1,vector<bool>(n+1,0));
	    int i = kp[0], j = kp[1], count = 0;
	    fun(i, j, tp, n, count,visited);
	    return ans;
	}};
0
auntylover10821 month ago
Why This is Giving Wrong Answer
class Solution 
{
    public:
    //Function to find out minimum steps Knight needs to reach target position.
    bool isVal(int x,int y,int N){
        return x>=0 && y>=0 && x<N && y<N ;
    }
    vector<pair<int,int>>movements = {
        {1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}
    };
   
	int minStepToReachTarget(vector<int>&knPos,vector<int>&Tarpos,int N)
	{
	   // int INF = 1e9+10;
	    // Code here
	    bool vis[N+1][N+1];
	    int lev[N+1][N+1];
	    for(int i=0;i<=N;i++){
	        for(int j=0;j<=N;j++){
	            vis[i][j]=false;
	            
	        }
	    }
	  queue<pair<int,int>>q;
        q.push({knPos[0],knPos[1]});
        vis[knPos[0]][knPos[1]] = 1;
        lev[knPos[0]][knPos[1]]=0;
        
        while(!q.empty()){
            pair<int,int>cp = q.front();
            int x = cp.first,y = cp.second;
            q.pop();
            for(auto moves:movements){
                int curx= x+moves.first , cury = y+moves.first;
                if(isVal(curx,cury,N)){
                    if(!vis[curx][cury]){
                        q.push({curx,cury});
                        vis[curx][cury]=1;
                        lev[curx][cury]= lev[x][y]+1;
                    }
                }
            }
             
        }
        return lev[Tarpos[0]][Tarpos[1]];
	}
};

We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.