Advertisement
imashutosh51

Minimum Steps by Knight to reach target

Aug 11th, 2022 (edited)
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. /*
  2. Logic: T.C: O(n*n) ie. no. of blocks of chess board
  3.        BFS is used here.
  4. */
  5.  
  6. class Solution {
  7.     public:
  8.     int minStepToReachTarget(vector<int>&s,vector<int>&d,int n){
  9.         s[0]--;s[1]--;d[0]--;d[1]--;
  10.        
  11.         deque<pair<pair<int,int>,int>> q;
  12.         q.push_back(make_pair(make_pair(s[0],s[1]),0));
  13.         vector <vector<bool>> check(n,vector <bool>(n,0));
  14.         check[s[0]][s[1]]=true;
  15.         int row[]={2,-2,1,1,2,-2,-1,-1};
  16.         int col[]={1,1,2,-2,-1,-1,-2,2};
  17.         int count=0;
  18.         while(q.size()){
  19.           pair<int,int> temp=q.front().first;
  20.           int dist=q.front().second;
  21.           q.pop_front();
  22.           if(temp.first==d[0] && temp.second==d[1]) return dist;
  23.           for(int i=0;i<8;i++){
  24.             int new_x=temp.first+row[i];
  25.             int new_y=temp.second+col[i];
  26.               if(new_x>=0 && new_y>=0 && new_x<n && new_y<n && !check[new_x][new_y]){
  27.                    q.push_back(make_pair(make_pair(new_x,new_y),dist+1));
  28.                    check[new_x][new_y]=true;
  29.                  
  30.               }
  31.           }
  32.         }
  33.         return -1;
  34.        
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement