we have an infinite chess board and we want to move from the position x1,y1 to the position x2,y2 using the minimum number of knight's moves.
I believe that this problem has a constant time solution but i couldn't approach it.
I would be grateful if any one explained the solution of this problem.
Thanks in advance.
I believe that this problem has a constant time solution but i couldn't approach it.
I would be grateful if any one explained the solution of this problem.
Thanks in advance.
int64 dist(int64 x1, int64 y1, int64 x2, int64 y2)
{
int64 dx = abs(x2-x1);
int64 dy = abs(y2-y1);
int64 lb=(dx+1)/2;
lb = max(lb, (dy+1)/2);
lb = max(lb, (dx+dy+2)/3);
while ((lb%2)!=(dx+dy)%2) lb++;
if (abs(dx)==1 && dy==0) return 3;
if (abs(dy)==1 && dx==0) return 3;
if (abs(dx)==2 && abs(dy)==2) return 4;
return lb;
}
here you go
Which book do you wanna suggest for Algorithmic problem solving?