Standard BFS question (nothing new) C++


#1
#include<bits/stdc++.h>
int Solution::knight(int A, int B, int C, int D, int E, int F){
    if(C==E && D==F) return 0;
    int dx[]= {-2, -2, -1, -1, 1, 2, 2, 1};
    int dy[]= {1, -1, 2, -2, 2, 1, -1, -2};
    queue<pair<int, int>> q;
    vector<vector<bool>> visited(A, vector<bool>(B, false));
    int steps= 0;
    q.push(make_pair(C-1, D-1));
    visited[C-1][D-1]= true;
    while(!q.empty()){
        int size= q.size();
        while(size--){
            auto p= q.front();
            q.pop();
            for(int i=0; i<8; i++){
                int r= p.first+ dx[i];
                int c= p.second+ dy[i];
                if(r==E-1 && c==F-1) return ++steps;
                if(r>=0 && c>=0 && r<A && c<B && !visited[r][c]){
                    q.push(make_pair(r, c));
                    visited[r][c]=true;
                }
            }
        }
        steps++;
    }
    return -1;
}