Created
December 27, 2023 05:04
-
-
Save primaryobjects/12d591bcc906810650cabdccb374c326 to your computer and use it in GitHub Desktop.
Minimum Time Visiting All Points https://leetcode.com/problems/minimum-time-visiting-all-points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Solved by calculating difference between each point diagonally and straight remainder. | |
const minTimeToVisitAllPoints = (points: number[][]): number => { | |
let moves = 0; | |
for (let i=1; i<points.length; i++) { | |
const dist_x = Math.abs(points[i-1][0] - points[i][0]); | |
const dist_y = Math.abs(points[i-1][1] - points[i][1]); | |
const dist_diag = Math.min(dist_x, dist_y); | |
const dist_straight = Math.abs(dist_y - dist_x); | |
moves += dist_diag + dist_straight; | |
} | |
return moves; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Solved by walking each step from one point to the next. | |
const minTimeToVisitAllPoints = (points: number[][]): number => { | |
const path = []; | |
let index = 1; | |
// Go through each point, starting at the initial point. | |
let point1 = points[0]; | |
while (index < points.length) { | |
const point2 = points[index]; | |
// Move closer to point2. | |
if (point1[0] < point2[0]) { | |
point1[0]++; | |
} | |
else if (point1[0] > point2[0]) { | |
point1[0]--; | |
} | |
if (point1[1] < point2[1]) { | |
point1[1]++; | |
} | |
else if (point1[1] > point2[1]) { | |
point1[1]--; | |
} | |
// Store the move. | |
path.push(point1); | |
// Check for waypoint. | |
if (point1[0] === point2[0] && point1[1] === point2[1]) { | |
// We've reached the next point. | |
point1 = point2; | |
index++; | |
} | |
} | |
return path.length; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment