forked from DeepanshuProgrammer/GeeksforGeeks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
17 August "Problem of the Day" Answer
47 lines (42 loc) · 1.24 KB
/
17 August "Problem of the Day" Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
GeeksforGeeks
The Question is :- "Knight Walk"
Answer :-
class Solution {
public:
int minStepToReachTarget(vector<int>&KnightPos, vector<int>&TargetPos, int n){
// Code here
vector<int> d={1,2,-1,2,1,-2,-1,-2,1};
// Code here
vector<vector<bool>> vis(n+1,vector<bool>(n+1,0));
int ans=0;
queue<pair<int,int>> q;
q.push({KnightPos[0],KnightPos[1]});
vis[KnightPos[0]][KnightPos[1]]=1;
while(!q.empty())
{
int sz=q.size();
while(sz--)
{
int x=q.front().first;
int y=q.front().second;
q.pop();
if(x==TargetPos[0] && y==TargetPos[1])
return ans;
for(int i=0;i<8;i++)
{
int a=x+d[i],b=y+d[i+1];
if(a>=1 && b>=1 && a<=n && b<=n && !vis[a][b])
{
q.push({a,b});
vis[a][b]=1;
}
}
}
ans++;
}
return -1;
}
};
Hope you understand the answer, and complete it.
Stay Connected for daily Problem of the Day answers.
Thank you All!