Matrix Cells in Distance Order - Problem
Matrix Cells in Distance Order
Imagine you're standing at a specific position in a grid-based city map, and you want to visit all locations in the city, starting with the closest ones first!
You are given four integers:
Your task: Return the coordinates of all cells in the matrix, sorted by their Manhattan distance from your current position
The Manhattan distance between two cells
Note: You may return coordinates with the same distance in any order.
Imagine you're standing at a specific position in a grid-based city map, and you want to visit all locations in the city, starting with the closest ones first!
You are given four integers:
rows, cols, rCenter, and cCenter. There is a rows ร cols matrix (like a city grid), and you are currently standing at coordinates (rCenter, cCenter).Your task: Return the coordinates of all cells in the matrix, sorted by their Manhattan distance from your current position
(rCenter, cCenter). Start with the smallest distance and work your way to the largest distance.The Manhattan distance between two cells
(r1, c1) and (r2, c2) is calculated as: |r1 - r2| + |c1 - c2|. This is like walking through city blocks - you can only move horizontally or vertically, not diagonally.Note: You may return coordinates with the same distance in any order.
Input & Output
example_1.py โ Basic 2x3 Matrix
$
Input:
rows = 1, cols = 2, rCenter = 0, cCenter = 0
โบ
Output:
[[0,0],[0,1]]
๐ก Note:
The distances are: (0,0)โ0, (0,1)โ1. So we return cells in order of increasing distance.
example_2.py โ 3x3 Matrix with Center
$
Input:
rows = 2, cols = 3, rCenter = 1, cCenter = 2
โบ
Output:
[[1,2],[0,2],[1,1],[1,0],[0,1],[0,0]]
๐ก Note:
Distances: (1,2)โ0, (0,2)โ1, (1,1)โ1, (1,0)โ2, (0,1)โ2, (0,0)โ3. Cells with same distance can be in any order.
example_3.py โ Single Cell Matrix
$
Input:
rows = 1, cols = 1, rCenter = 0, cCenter = 0
โบ
Output:
[[0,0]]
๐ก Note:
Only one cell exists, so it's returned as the only element with distance 0.
Constraints
- 1 โค rows, cols โค 100
- 0 โค rCenter < rows
- 0 โค cCenter < cols
Visualization
Tap to expand
Understanding the Visualization
1
Center Point
Start at (rCenter, cCenter) with distance 0 - this is where the stone hits the water
2
Distance 1 Ring
Cells at Manhattan distance 1 form a diamond shape around the center
3
Distance 2 Ring
The next ring expands outward, containing all cells at distance 2
4
Continue Expansion
Keep expanding until all matrix cells are covered
Key Takeaway
๐ฏ Key Insight: Manhattan distance creates predictable square 'ripples' that expand outward. By using bucket sort on the limited range of distance values, we can collect coordinates in perfect distance order without expensive sorting operations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code