Easy BFS approach in C++


#1
struct node
{
    int x,y,dis;
    node(int x,int y,int dis)
    {
        this->x=x;
        this->y=y;
        this->dis=dis;
    }
};
bool is_inside(int i,int j,int row,int col)
{
    return i>=1 && j>=1 && i<=row && j<=col;
}
int Solution::knight(int A, int B, int C, int D, int E, int F) 
{
    queue<node>q;
    vector<vector<bool>>vis(A+1,vector<bool>(B+1,false));
    vector<vector<int>>pos={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
    node obj(C,D,0);
    q.push(obj);
    vis[C][D]=true;
    while(!q.empty())
    {
        node cell=q.front();
        q.pop();
        if(cell.x==E && cell.y==F)
        {
            return cell.dis;
        }
        for(int i=0;i<8;i++)
        {
            int row=cell.x+pos[i][0],col=cell.y+pos[i][1];
            if(is_inside(row,col,A,B) && !vis[row][col])
            {
                vis[row][col]=true;
                node obj_(row,col,cell.dis+1);
                q.push(obj_);
            }
        }
    }
    return -1;
}