Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic: T.C: O(n*n) ie. no. of blocks of chess board
- BFS is used here.
- */
- class Solution {
- public:
- int minStepToReachTarget(vector<int>&s,vector<int>&d,int n){
- s[0]--;s[1]--;d[0]--;d[1]--;
- deque<pair<pair<int,int>,int>> q;
- q.push_back(make_pair(make_pair(s[0],s[1]),0));
- vector <vector<bool>> check(n,vector <bool>(n,0));
- check[s[0]][s[1]]=true;
- int row[]={2,-2,1,1,2,-2,-1,-1};
- int col[]={1,1,2,-2,-1,-1,-2,2};
- int count=0;
- while(q.size()){
- pair<int,int> temp=q.front().first;
- int dist=q.front().second;
- q.pop_front();
- if(temp.first==d[0] && temp.second==d[1]) return dist;
- for(int i=0;i<8;i++){
- int new_x=temp.first+row[i];
- int new_y=temp.second+col[i];
- if(new_x>=0 && new_y>=0 && new_x<n && new_y<n && !check[new_x][new_y]){
- q.push_back(make_pair(make_pair(new_x,new_y),dist+1));
- check[new_x][new_y]=true;
- }
- }
- }
- return -1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement