Bfs c++ . simple n easy


#1

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