DEV Community

Cover image for 🧭 Beginner-Friendly Guide 'Minimum Time Visiting All Points' – LeetCode 1266 (C++, Python, JavaScript)
Om Shree
Om Shree

Posted on

🧭 Beginner-Friendly Guide 'Minimum Time Visiting All Points' – LeetCode 1266 (C++, Python, JavaScript)

Navigating a 2D grid efficiently is a fundamental skill in both competitive programming and game development. This problem challenges us to find the shortest path between multiple points when we have the freedom to move diagonally.


Problem Summary

You're given:

  • An array of coordinates representing points on a 2D plane.
  • The ability to move horizontally, vertically, or diagonally.
  • A requirement to visit the points in the exact order they appear in the list.

Your goal:

  • Calculate the minimum total time (in seconds) required to visit every point in the sequence.

Example:

Image description : Example

Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]

Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds


Intuition

The key to solving this problem lies in understanding how diagonal movement works. In a standard grid, moving from to usually takes steps if you can only move horizontally or vertically (this is known as Manhattan Distance).

However, because we can move diagonally, we can cover one unit of horizontal distance and one unit of vertical distance simultaneously in just 1 second. This means the time taken to travel between two points is determined by the "longer" of the two distances (horizontal or vertical). This is formally known as the Chebyshev Distance.

For any two consecutive points, we calculate the absolute difference in their coordinates and their coordinates. The time taken to travel between them is simply the maximum of these two values. We repeat this for every pair of consecutive points in the list and sum the results.


Code Blocks

C++

class Solution {
public:
    int minTimeToVisitAllPoints(vector<vector<int>>& points) {
        int totalTime = 0;

        for (int i = 1; i < points.size(); ++i) {
            // The time to move between two points is the maximum of the 
            // horizontal and vertical distances.
            int dx = abs(points[i][0] - points[i - 1][0]);
            int dy = abs(points[i][1] - points[i - 1][1]);
            totalTime += max(dx, dy);
        }

        return totalTime;
    }
};

Enter fullscreen mode Exit fullscreen mode

Python

class Solution:
    def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
        total_time = 0

        for i in range(1, len(points)):
            # Calculate absolute differences for x and y coordinates
            dx = abs(points[i][0] - points[i - 1][0])
            dy = abs(points[i][1] - points[i - 1][1])

            # The maximum of the two represents the minimum time needed
            total_time += max(dx, dy)

        return total_time

Enter fullscreen mode Exit fullscreen mode

JavaScript

/**
 * @param {number[][]} points
 * @return {number}
 */
var minTimeToVisitAllPoints = function(points) {
    let totalTime = 0;

    for (let i = 1; i < points.length; i++) {
        // Find the absolute difference between current and previous coordinates
        let dx = Math.abs(points[i][0] - points[i - 1][0]);
        let dy = Math.abs(points[i][1] - points[i - 1][1]);

        // Add the maximum difference to the total time
        totalTime += Math.max(dx, dy);
    }

    return totalTime;
};

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Chebyshev Distance: In grids where diagonal movement is allowed and costs the same as cardinal movement, the distance between points is .
  • Greedy Optimization: We always prefer diagonal moves as long as possible because they cover the most ground in the least amount of time.
  • Coordinate Geometry: Breaking down 2D movements into their and components is a vital technique for solving spatial problems.

Final Thoughts

This problem is a fantastic introduction to how movement logic works in software. While it seems simple, this exact logic is used in pathfinding algorithms for video games and logistics software to estimate travel times. Understanding how different "distance metrics" (like Manhattan vs. Chebyshev) change your result is crucial for building accurate simulations. In a real-world system, like a delivery drone or a robot on a factory floor, these calculations form the backbone of movement efficiency.

Top comments (0)