Advertisement
vaibhav1906

GFG Knight Walk Problem (Class 23)

Jul 29th, 2021
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. //GFG Knight Walk Problem (Class 23) https://practice.geeksforgeeks.org/problems/knight-walk4521/1
  2.  
  3. struct box{
  4. int x;
  5. int y;
  6. int step;
  7. };
  8. class Solution {
  9. public:
  10. int minStepToReachTarget(vector<int>&K, vector<int>&T, int N){
  11. // Code here
  12.  
  13. vector<vector<bool>>v(N+1,vector<bool>(N+1,false));
  14.  
  15. queue<box> q;
  16.  
  17. int xpos[8] = {2,2,-2,-2,1,1,-1,-1};
  18. int ypos[8] = {1,-1,1,-1,2,-2,2,-2};
  19.  
  20. q.push({K[0],K[1],0});
  21.  
  22. while(q.size()!=0){
  23.  
  24. int x = q.front().x;
  25. int y = q.front().y;
  26. int step = q.front().step;
  27. q.pop();
  28.  
  29. if(x==T[0] && y==T[1])return step;
  30.  
  31. for(int i =0; i<8; i++){
  32. int xnew = x+xpos[i];
  33. int ynew = y+ypos[i];
  34.  
  35. if(xnew>=1 && ynew>=1 && xnew<=N && ynew<=N && v[xnew][ynew]==false){
  36. q.push({xnew,ynew,step+1});
  37. v[xnew][ynew] = true;
  38. }
  39.  
  40. }
  41.  
  42.  
  43.  
  44. }
  45.  
  46. return 0;
  47.  
  48. }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement