1266. Minimum Time Visiting All Points

Here, you are given 2D vector containing coordinates. And you have to return the minimum number of times to visit all the coordinates.

You can move three way :

  1. Move Vertically by one unite,

  2. Move Horizontally by one unite,

  3. move diagonally by sqrt(2) unite ( Which mean actually 1 unite)

how can the minimum time to visit all coordinates be determined?

Let's consider the following scenario: Let's suppose we are in (1,1) and our target distance is (5,5) so if we visit (1,1) to (5,5) then first we need to move Horizontally 5 unite (1,1)->(2,1)->(3,1)->(4,1)->(5,1) then our (1,1) will be (5,1) and then we need to increase y 5 unite to react distance and it will (5,5) (5,1)->(5,2)->(5,3)->(5,4)->(5,5) so how many moves or seconds are needed to reach this point? 5+5 = 10;

Now if we traverse diagonally, it takes only 5 seconds to reach our target. how?

(1,1) -> (2,2) ->(3,3)->(4,4)->(5,5) takes 5 unit to reach here.

so we see if we move diagonally then we need minimal time to reach the target.

what if (1,1) is our current state and (5,6) is our target ?

can we move diagonally? Yes!!! We will move diagonally first then just go vertically to reach the target. and it takes 6 minutes.

So, we only need to calculate the distance between two coordinates. (x1,y1) , (x2,y2) = max((x2-x1),(y2-y1)) will take the max value cause if x and y are not the same then we need to move Horizontally or Vertically.

Considering constraints where coordinates can be negative, we take the absolute value. The final equation is: ans = max(abs(x2-x1), abs(y2-y1)), where ans represents the minimum time to reach the target.

   int minTimeToVisitAllPoints(vector<vector<int>>& points) {
    int ans = 0;
    for(int i=0; i<points.size()-1; i++){
        int curx = points[i][0];
        int cury = points[i][1];

        int targetx = points[i+1][0];
        int targety = points[i+1][1];

        ans += max(abs(targetx-curx), abs(targety-cury));
    }