반응형
https://leetcode.com/problems/minimum-time-visiting-all-points/description/
Minimum Time Visiting All Points - LeetCode
Can you solve this real interview question? Minimum Time Visiting All Points - On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. You can
leetcode.com
vector를 다뤄본 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 ans를 선언 후 0으로 초기화합니다.
📔 풀이과정
순서대로 좌표를 방문해야되므로 최적화가 필요 없이 바로 현재 점과 다음 방문할 점 간의 이동 횟수를 계산해 ans에 더해주면 됩니다.
points의 원소를 순회하며 points[i]는 curPoint고 points[i+1]은 nextPoint일 때
$${현재\quad이동횟수 += max(abs(nextPoint[0] - curPoint[0]), abs(nextPoint[1] - curPoint[1]))}$$
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
int minTimeToVisitAllPoints(vector<vector<int>>& points) {
int ans = 0;
for(int i = 0; i < points.size() - 1; i++) {
vector<int> curPoint = points[i];
vector<int> nextPoint = points[i+1];
ans += max(abs(nextPoint[0] - curPoint[0]), abs(nextPoint[1] - curPoint[1]));
}
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.