Simple and easy to understand bfs solution


#1

int x[]={-2,-1,1,2,2,1,-1,-2};
int y[]={1,2,2,1,-1,-2,-2,-1};

struct cord {
int xc;
int yc;
int count;
};

int Solution::knight(int A, int B, int xs, int ys, int xd, int yd) {
set<pair<int,int>>vis;
queueq;
cord c={xs,ys,0};
q.push©;
while(!q.empty())
{
cord pnt=q.front();
if(pnt.xc==xd && pnt.yc==yd)
return pnt.count;
q.pop();
pair<int,int>p=make_pair(pnt.xc,pnt.yc);
if(!vis.count§)
{
vis.insert(make_pair(p.first,p.second));
for(int i=0;i<8;i++)
{
int px=pnt.xc+x[i];
int py=pnt.yc+y[i];
if((px>0 && px<=A) && (py>0 && py<=B))
{
if(px==xd && py==yd)
return pnt.count+1;
else
q.push({px,py,pnt.count+1});
}
}
}
}
return -1;
}