Imagine you're standing at a specific location (x, y) on a grid, and there are several points scattered around you. You can only move to points that are either directly horizontal (same x-coordinate) or directly vertical (same y-coordinate) from your current position - like a rook in chess!
Your task is to find the closest valid point using Manhattan distance (the sum of horizontal and vertical distances). If multiple points are equally close, choose the one with the smallest index.
Input: Your current coordinates (x, y) and an array points where each points[i] = [ai, bi] represents a point at (ai, bi).
Output: The index of the nearest valid point, or -1 if no valid points exist.
Manhattan Distance Formula: |x1 - x2| + |y1 - y2|
Input & Output
Visualization
Time & Space Complexity
Must examine each point once to check validity and calculate distance
Only using a few variables to track the best result
Constraints
- 1 โค points.length โค 104
- points[i].length == 2
- 1 โค x, y, ai, bi โค 104
- All coordinates are positive integers