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 or return -1 if its not possible.
 
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
abs_bharat_sai3 days ago
>> Shortest number of steps BFS is the go to solution
int minStepToReachTarget(vector<int> &ini,vector<int> &tar,int n){
    // Code here
    queue<pair<int, int>> q;
    int cnt = 0;
    int r[8] = {2, 1, -1, -2, -2, -1, 1, 2};
    int c[8] = {1, 2, 2, 1, -1, -2, -2, -1};
    vector<vector<int>> vis(n, vector<int>(n, 0));
    q.push({ini[0]-1, ini[1]-1});
    vis[ini[0]-1][ini[1]-1] = 1;
    while(!q.empty()){
        int size = q.size();
        while(size--){
            int x = q.front().first;
            int y = q.front().second;
            q.pop();
            if(x == tar[0]-1 && y == tar[1]-1){
                return cnt;
            }
            for(int i = 0 ; i < 8; i++){
                int cx = x + r[i];
                int cy = y + c[i];
                if(cx >= 0 && cx < n && cy >= 0 && cy < n && !vis[cx][cy]){
                    q.push({cx, cy});
                    vis[cx][cy] = 1;
                }
            }
           
        }
        cnt++;
    }
    return -1;
}
0
rhythmanand6Premium4 days ago
class Pair{
       int x;
       int y;
       Pair(int x, int y){
           this.x = x;
           this.y = y;
       }
   }
   
    public int minStepToReachTarget(int KnightPos[], int TargetPos[], int N)
    {
        // Code here
        int x = KnightPos[0]-1;
        int y = KnightPos[1]-1;
        
        int di[]={-1,1,1,-1,-2,-2,2,2};
	    int dj[]={-2,-2,2,2,-1,1,-1,1};
        
        boolean[][] visited = new boolean[N][N];
        
        Queue<Pair> q = new LinkedList<>();
        q.add(new Pair(x, y));
        visited[x][y] = true;
        
        int count = 0;
        while(!q.isEmpty()){
            int size = q.size();
            count++;
            
            while(size-->0){
                Pair cur = q.poll();
                if(cur.x==TargetPos[0]-1 && cur.y==TargetPos[1]-1) return count-1;
                for(int i=0; i<8; i++){
                    int nextX = cur.x + di[i];
                    int nextY = cur.y + dj[i];
                    
                    if(nextX>=0 && nextX<N && nextY>=0 && nextY<N && !visited[nextX][nextY]){
                        q.add(new Pair(nextX, nextY));
                        visited[nextX][nextY] = true;
                    }
                }
            }
        }
        
        return -1;
        
    }
0
k_jain5 days ago

// } Driver Code Ends

class Pair{
    int x; 
    int y;
    Pair(int x, int y){
        this.x = x;
        this.y = y;
    }
}
class Solution
{
    //Function to find out minimum steps Knight needs to reach target position.
    public int minStepToReachTarget(int KnightPos[], int TargetPos[], int n)
    {
        // Code here
        //like rotten oranges proble
        // we will perform bfs becuase from every position we want to check it's adjacnet position
        
        //queue is needed for bfs
        Queue<Pair> q = new LinkedList<>();
        
        //starting cordinates
        int start_x = KnightPos[0] - 1; //converting into 0-based index
        int start_y = KnightPos[1] - 1;
        
        int target_x = TargetPos[0] - 1 ;
        int target_y = TargetPos[1] - 1 ;
        
        if(start_x == target_x && start_y == target_y)
            return 0;
        
        //for checking the visited positon;
        boolean[][] visited = new boolean[n][n];
        
        for(boolean[] temp : visited){
            Arrays.fill(temp, false);
        }
        
        //for counting steps
        int steps = 0;
        
        visited[start_x][start_y] = true;
        q.offer(new Pair(start_x, start_y));
        
        
        int[] ax = new int[]{-1, 1, 2, -2, -1, 1, 2, -2};

        int[] ay = new int[]{2, 2, 1, 1, -2, -2, -1, -1};
        
        while(!q.isEmpty()){
            
            int size = q.size();
    
            steps++;
            //for every step we are finding 8 possible moves of the knight
            while(size != 0){
            
            //pop out the possible step
            Pair p = q.poll();
                int x = p.x;
                int y = p.y;
                
                //may be this x, y are our required cordinate
                if(x == target_x && y == target_y)
                    return steps-1;
                
                //now choose only the valid position out of these 8
                for(int i = 0; i<8; i++){
                    if(isValid(x+ax[i], y+ay[i],n, visited) == true)
                    {
                        //mark this as visited;
                        visited[x+ax[i]][y+ay[i]] = true;
                        q.offer(new Pair(x+ax[i], y + ay[i]));
                    }
                }
                size--;
            }
        }
        return -1;
    }
    
    private boolean isValid(int x, int y, int n, boolean[][] visited){
        if(x>=0 && x<n && y>=0 && y<n && visited[x][y] == false)
            return true;
        return false;
    }
}
+1
knightgod1 week ago
class Solution
{
 bool isValid(int x,int y,int N){
        if(x>=0 && x<N && y>=0 && y<N) return true;
        return false;
    }
int minStepToReachTarget(vector<int>&KnightPos,
	                     vector<int>&TargetPos,int N)
	{
	    int dx[] = {2,2,-2,-2,1,1,-1,-1};
        int dy[] = {1,-1,1,-1,2,-2,2,-2};
        vector<vector<bool>> visited(N,vector<bool>(N,false));
        queue<pair<int,int>> q;
     
        vector<vector<int>> dist(N,vector<int>(N,0));
        
        q.push(make_pair(KnightPos[0]-1,KnightPos[1]-1));
        
        visited[KnightPos[0]-1][KnightPos[1]-1] = true;
        
        while(!q.empty()){
            pair<int,int> currCell=q.front();
            q.pop();
  
            for(int i=0;i<8;i++){
               int x = currCell.first + dx[i];
               int y = currCell.second + dy[i];
               
        if(currCell.first == TargetPos[0]-1 && 
           currCell.second == TargetPos[1]-1)
               
            return dist[currCell.first][currCell.second];
                
               if(isValid(x,y,N) && !visited[x][y]){
                   q.push(make_pair(x,y));
                   visited[x][y]=true;
    dist[x][y] = dist[currCell.first][currCell.second] + 1;
               }
            }
        }
       return -1;
    
	    // Code here
	}
+1
69rw2mwqg20lg2xtig73okg0jp76p59ixg8orzbs1 week ago
int dx[8] = {2,2,-2,-2,1,-1,1,-1};
int dy[8] = {1,-1,1,-1,2,2,-2,-2};
vector<vector<int>> dist;
    
bool check(int x,int y,int N){
    return (x >= 0 && y >= 0 && x <= N && y <= N);
}
    
int minStepToReachTarget(vector<int> &KnightPos,vector<int> &TargetPos,int N){
	dist = vector<vector<int>>(N+1,vector<int>(N+1,0));
	if(KnightPos[0] == TargetPos[0] && KnightPos[1] == TargetPos[1]) return 0;
    queue<pair<int,int>> q;
    q.push(make_pair(KnightPos[0],KnightPos[1]));
    while(!q.empty()){
        pair<int,int> xx = q.front();
        q.pop();
        for(int i=0;i<8;i++){
            if(check(xx.first + dx[i],xx.second + dy[i],N) && (dist[xx.first + dx[i]][xx.second + dy[i]]) == 0){
                dist[xx.first + dx[i]][xx.second + dy[i]] = dist[xx.first][xx.second] + 1;
                q.push(make_pair(xx.first + dx[i],xx.second + dy[i]));
            }
        }
    }
    if(dist[TargetPos[0]][TargetPos[1]] == 0) return -1;
    return dist[TargetPos[0]][TargetPos[1]];
}
0
rajubugude1 week ago
PYTHON CODE (USING BFS)
from queue import Queue
direc = [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,-1]]

class Solution:
    def check(self,i,j,n,vis):
        return i >= 0 and j >= 0 and i < n and j < n and vis[i][j] == 0

	def minStepToReachTarget(self, KPos, TargetPos, n):
	    KPos[0] = KPos[0]-1; KPos[1] = KPos[1]-1
	    TargetPos[0] = TargetPos[0]-1; TargetPos[1] = TargetPos[1]-1
	    
	    if KPos == TargetPos:
	        return 0
	    q = Queue()
	    q.put([KPos[0],KPos[1],0])
	    
	    vis = [[0 for _ in range(n)] for _ in range(n)]
	    vis[KPos[0]][KPos[1]] = 1
	    
	    while not q.empty():
	        x,y,d = q.get()
            if x == TargetPos[0] and y == TargetPos[1]:
                return d
	        for u,v in direc:
	            p = x + u
	            r = y + v
	            if self.check(p,r,n,vis):
	                q.put([p,r,d+1])
	                vis[p][r] = 1
	                
	    return -1   
+1
20192851 week ago
this solution is giving TLE (10/20 case)
 pls tell what am in doing wrong ?
 
public:   //Function to find out minimum steps Knight needs to reach target position.int dx[8]={-2,-1,1,2,2,1,-1,-2};int dy[8]={1,2,2,1,-1,-2,-2,-1};bool isvalid(int x,int y, int n,vector<vector<bool>> vis){    if(x<1||y<1||x>n||y>n) return false;    if(vis[x][y]) return false;    return true;}int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N){   vector<vector<bool>> vis(N+1,vector<bool>(N+1,false));   vector<vector<int>> d(N+1,vector<int>(N+1,-1));         queue<pair<int,int>> q;   q.push({KnightPos[0],KnightPos[1]});   vis[KnightPos[0]][KnightPos[1]] =true;   d[KnightPos[0]][KnightPos[1]] =0;      while(!q.empty()){       pair<int , int> p = q.front();       q.pop();       for(int i=0;i<8;i++){           int cx=p.first +dx[i];           int cy=p.second +dy[i];           if( isvalid(cx,cy,N,vis) ){               vis[cx][cy]=true;               q.push({cx,cy});               d[cx][cy]=d[p.first][p.second]+1;           }       }          }   return d[TargetPos[0] ][TargetPos[1] ];}
+1
007msr0071 week ago
C++ Code:
	int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int N)
	{
	    // Code here
	    if(KnightPos[0]==TargetPos[0] && KnightPos[1]==TargetPos[1]) return 0;
	    int dx[8]={1,2,-2,-1,-1,-2,2,1};
	    int dy[8]={-2,-1,1,2,-2,-1,1,2};
	    vector<vector<int>>dis(N,vector<int>(N,0));
	    queue<vector<int>>q;
	    q.push({KnightPos[0]-1,KnightPos[1]-1});
	    while(!q.empty())
	    {
	        auto v = q.front();
	        q.pop();
	        int x = v[0];
	        int y=v[1];
	        for(int i=0;i<8;i++)
	        {
	            if(x+dx[i]>=0 && x+dx[i]<N && y+dy[i]>=0 && y+dy[i]<N && dis[x+dx[i]][y+dy[i]]==0) 
	             {
	                 dis[x+dx[i]][y+dy[i]] = dis[x][y]+1;
	                 q.push({x+dx[i],y+dy[i]});
	             }
	        }
	    }
	 return dis[TargetPos[0]-1][TargetPos[1]-1];  
	}
0
priyanshu543212 weeks ago

class Solution 
{
    private:
    vector<pair<int,int>> getChild(pair<int,int> pos,int n)
    {
        vector<pair<int,int>> ans;
        int i=pos.first;
        int j=pos.second;
        if(i-2>=0)
        {
            if(j-1>=0)
                ans.push_back({i-2,j-1});
            if(j+1<n)
                ans.push_back({i-2,j+1});
        }
        if(i+2<n)
        {
            if(j-1>=0)
                ans.push_back({i+2,j-1});
            if(j+1<n)
                ans.push_back({i+2,j+1});
        }
        if(j-2>=0)
        {
            if(i-1>=0)
                ans.push_back({i-1,j-2});
            if(i+1<n)
                ans.push_back({i+1,j-2});
        }
        if(j+2<n)
        {
            if(i-1>=0)
                ans.push_back({i-1,j+2});
            if(i+1<n)
                ans.push_back({i+1,j+2});
        }
        return ans;
    }
    public:
	int minStepToReachTarget(vector<int>&KnightPos,vector<int>&TargetPos,int n)
	{
	    queue<pair<int,int>> q;
	    vector<vector<int>> vis(n,vector<int>(n,0));
	    vector<vector<pair<int,int>>> parent(n,vector<pair<int,int>>(n));
	    q.push({KnightPos[0]-1,KnightPos[1]-1});
	    vis[KnightPos[0]-1][KnightPos[1]-1]=1;
	    parent[KnightPos[0]-1][KnightPos[1]-1]={-1,-1};
	    int ans=0;
	    while(!q.empty())
	    {
	        pair<int,int> front=q.front();
	        q.pop();
	        for(auto child:getChild(front,n))
	        {
	            if(vis[child.first][child.second]!=1)
	            {
	                vis[child.first][child.second]=1;
	                parent[child.first][child.second]=front;
	                q.push(child);
	            }
	        }
	        if(vis[TargetPos[0]-1][TargetPos[1]-1]==1)
	            break;
	    }
	    int i=TargetPos[0]-1;
	    int j=TargetPos[1]-1;
	    while(i!=-1)
	    {
	        int x=parent[i][j].first;
	        int y=parent[i][j].second;
	        i=x;
	        j=y;
	        ans++;
	    }
	    return ans-1;
	}
};


0
rajkeshari7462 weeks ago
 vector<vector<int>> level;
   vector<vector<bool>> vis;
   
   vector<pair<int,int>> moves={{-2,-1},{-2,1},{2,-1},{2,1},{1,2},{-1,-2},{-1,2},{1,-2}};
   
   bool isvalid(pair<int,int> i , int x , int y , int N)
   {
       return (((x+i.first)>=0 && (x+i.first)<N) && ((y+i.second)>=0 && (y+i.second)<N)) && !vis[x+i.first][y+i.second]; 
   }
   
   
int minStepToReachTarget(vector<int>&KP,vector<int>&TP,int N)
{
    level.resize(N,vector<int>(N,0));
    vis.resize(N,vector<bool>(N,false));
    
    queue<pair<int,int>> q;
    q.push({KP[0]-1,KP[1]-1});
    vis[KP[0]-1][KP[1]-1]=true;
    level[KP[0]-1][KP[1]-1]=0;
    
    while(!q.empty())
    {
        pair<int,int> temp=q.front();
        q.pop();
        int x=temp.first;
        int y=temp.second;
        
        for(auto i:moves)
        {
            if(isvalid(i,x,y,N))
            {
                q.push({x+i.first,y+i.second});
                vis[x+i.first][y+i.second]=true;
                level[x+i.first][y+i.second]=level[x][y]+1;
            }
        }
    }
    
    return level[TP[0]-1][TP[1]-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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.