A solution using pairs and BFS


#1

int Solution::knight(int A, int B, int C, int D, int E, int F) {
vector<vector> vec(A+1, vector (B+1, -1));
queue<pair<int,int>>q;
pair<int,int>temp;
q.push(make_pair(C,D));
vec[C][D]=0;
int ret=0;
while(!q.empty())
{
temp=q.front();
int x=temp.first;
int y=temp.second;
q.pop();
if(x==E&&y==F)
return vec[x][y];
if(x+1<=A&&y+2<=B&&vec[x+1][y+2]==-1)
{
q.push(make_pair(x+1,y+2));
vec[x+1][y+2]=vec[x][y]+1;
}
if(x+1<=A&&y-2>0&&vec[x+1][y-2]==-1)
{
q.push(make_pair(x+1,y-2));
vec[x+1][y-2]=vec[x][y]+1;

        }
        if(x+2<=A&&y-1>0&&vec[x+2][y-1]==-1)
        {
            q.push(make_pair(x+2,y-1)); 
            vec[x+2][y-1]=vec[x][y]+1;
        }
        if(x+2<=A&&y+1<=B&&vec[x+2][y+1]==-1)
        {
            q.push(make_pair(x+2,y+1)); 
            vec[x+2][y+1]=vec[x][y]+1;
        }
        if(x-1>0&&y+2<=B&&vec[x-1][y+2]==-1)
        {
            q.push(make_pair(x-1,y+2));
            vec[x-1][y+2]=vec[x][y]+1;
        }
        if(x-1>0&&y-2>0&&vec[x-1][y-2]==-1)
        {
            q.push(make_pair(x-1,y-2));
            vec[x-1][y-2]=vec[x][y]+1;

        }
        if(x-2>0&&y-1>0&&vec[x-2][y-1]==-1)
        {
            q.push(make_pair(x-2,y-1)); 
            vec[x-2][y-1]=vec[x][y]+1;
        }
        if(x-2>0&&y+1<=B&&vec[x-2][y+1]==-1)
        {
            q.push(make_pair(x-2,y+1)); 
            vec[x-2][y+1]=vec[x][y]+1;
        }
    }
    return -1;

}