Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool check(int i ,int j,int n){
- if(i>=0 && i<=n-1 && j>=0 && j<=n-1) return true;
- return false;
- }
- int minStepToReachTarget(int knightPos[], int targetPos[], int N) {
- vector<vector<int>> visit(N,vector<int>(N,-1));
- queue<pair<pair<int ,int>,int>> q;
- visit[knightPos[0]-1][knightPos[1]-1]=0;
- q.push({{knightPos[0]-1,knightPos[1]-1},0});
- int steps=0;
- vector<pair<int,int>> dir = {{1,2},{-1,-2},{-2,-1},{-2,2},{-1,2},{1,2},{2,1},{2,-1}};
- while(!q.empty()){
- pair<pair<int,int>,int> p = q.front();
- q.pop();
- if(p.first==make_pair(targetPos[0]-1,targetPos[1]-1)){
- steps = p.second;
- break;
- }
- for(auto x:dir){
- pair<int,int> cor = make_pair(p.first.first + x.first,p.first.second + x.second);
- if (visit[cor.first][cor.second]==-1 && check(cor.first,cor.second,N)){
- visit[cor.first][cor.second]=0;
- q.push(make_pair(cor,p.second+1));
- }
- }
- }
- return steps;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement