C++ BFS Simple and Concise


#1
bool issafe(int x,int y,int a, int b)
{
    return !(x<=0 || y<=0 || x>a || y>b);
}
int Solution::knight(int a, int b, int c, int d, int e, int f) {
    if(!issafe(c,d,a,b) || !issafe(e,f,a,b)) return -1;
    if(c == e && d == f) return 0;
    int count = 0;
    queue<pair<int,int>> q;
    q.push(make_pair(c,d));
    vector<vector<bool>>vis(a+1,vector<bool>(b+1,0));
    vis[c][d] = 1;
    vector<int> r = {2,1,-1,-2,-2,-1,1,2};
    vector<int> col = {1,2,2,1,-1,-2,-2,-1};
    while(!q.empty())
    {
        int x = q.size();
        while(x--)
        {
            auto[u,v] = q.front();
            q.pop();
            for(int i=0; i<8; i++)
            {
                if(issafe(u+r[i],v+col[i],a,b) && !vis[u+r[i]][v+col[i]])
                {
                    if(u+r[i] == e && v + col[i] == f)
                    {
                        return count+1;
                    }
                    vis[u+r[i]][v+col[i]] = true;
                    q.push(make_pair(u+r[i],v+col[i]));
                }
            }
        }
        ++count;
    }
    return -1;
}