Sweet and simple soln with tuple data structure


#1

bool issafe(int p,int s,int x,int y,vector vis[])
{
return (p>=1 && s>=1 && p<=x && s<=y && !vis[p][s] );
}
int Solution::knight(int A, int B, int C, int D, int E, int F)
{
vectorvis[A+1];
for(int i=0;i<A+1;i++)
vis[i].resize(B+1,false);

queue<tuple<int,int,int>> q;
q.push(make_tuple(C,D,0));

while(!q.empty())
{
    tuple<int,int,int> t = q.front();
        q.pop();
    
    if(get<0>(t) == E && get<1>(t) == F)
        return get<2>(t);
    
    static int row[] = {-2,-2,-1,-1,1,1,2,2};
    static int col[] = {-1,1,-2,2,-2,2,-1,1};
    for(int k=0;k<8;k++)
    {
        int p = get<0>(t)+row[k];
        int s = get<1>(t)+col[k];
        if(issafe(p,s,A,B,vis))
        {
            vis[p][s] = true;
            q.push(make_tuple(p,s,get<2>(t)+1));
        }
    }
}
return -1;

}