Matrix Cells in Distance Order - Problem
You are given four integers rows, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2| (Manhattan distance).
Input & Output
Example 1 — Small Matrix
$
Input:
rows = 1, cols = 2, rCenter = 0, cCenter = 0
›
Output:
[[0,0],[0,1]]
💡 Note:
Only 2 cells: (0,0) at distance 0 and (0,1) at distance 1. Manhattan distance from (0,0): |0-0|+|0-0|=0 for (0,0), |0-0|+|1-0|=1 for (0,1).
Example 2 — Center Position
$
Input:
rows = 2, cols = 2, rCenter = 0, cCenter = 1
›
Output:
[[0,1],[0,0],[1,1],[1,0]]
💡 Note:
Center (0,1): distance 0. Adjacent cells (0,0) and (1,1) at distance 1. Diagonal (1,0) at distance 2. Order: d=0 → d=1 → d=1 → d=2.
Example 3 — Corner Center
$
Input:
rows = 2, cols = 3, rCenter = 1, cCenter = 2
›
Output:
[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
💡 Note:
Center at corner (1,2). Distances: (1,2)=0, (0,2)=1, (1,1)=1, (0,1)=2, (1,0)=2, (0,0)=3. Cells are naturally grouped by distance levels.
Constraints
- 1 ≤ rows, cols ≤ 100
- 0 ≤ rCenter < rows
- 0 ≤ cCenter < cols
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
2×3 matrix with center at (0,1)
2
Calculate Distances
Manhattan distance from each cell to center
3
Sort by Distance
Return coordinates in increasing distance order
Key Takeaway
🎯 Key Insight: Manhattan distance creates natural concentric layers around the center point
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code