C++ code to find total time to pull the box by rabbit

Suppose we have two coordinates (x1, y1) and (x2, y2). A rabbit is pulling food box. He is attached with a rope with only 1 unit sized rope. Rabbit will pull the box to where it is standing before moving out of the way in the same direction by 1 unit. Rabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for it to be in exactly 1 unit away from the box. If he wants to pull the box again, it must go to a point next to the box. Rabbit can start at any point. It takes 1 second to travel 1 unit at any direction. We have to find the minimum amount of time it needs to move the box from start location to end location.

So, if the input is like x1 = 1; y1 = 1; x2 = 2; y2 = 2, then the output will be 4, because Rabbit can start at the point (2,1). It pulls the box to (2,1) while it is in (3,1). Then moves to (3,2) and then to (2,2) without pulling the box. Then, pulls the box to (2,2) while moving to (2,3). It takes 4 seconds.


To solve this, we will follow these steps −

s := 0
if x1 is not equal to x2 and y1 is not equal to y2, then:
   s := |x2 - x1| + |y2 - y1|
   s := |x2 - x1| + |y2 - y1|
return s


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int x1, int y1, int x2, int y2){
   int s = 0;
   if (x1 != x2 && y1 != y2)
      s = abs(x2 - x1) + abs(y2 - y1) + 2;
      s = abs(x2 - x1) + abs(y2 - y1);
   return s;
int main(){
   int x1 = 1;
   int y1 = 1;
   int x2 = 2;
   int y2 = 2;
   cout << solve(x1, y1, x2, y2) << endl;


1, 1, 2, 2