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
Matrix Cells in Distance Order INPUT (0,0) (0,1) Red = Center (rCenter, cCenter) rows = 1, cols = 2 rCenter = 0, cCenter = 0 Manhattan Distance: |r1-r2| + |c1-c2| dist(0,0) = 0 dist(0,1) = 1 ALGORITHM (BFS) 1 Start at Center Add (0,0) to queue 2 Process Queue Dequeue, add to result 3 Explore Neighbors 4 directions (up,down,L,R) 4 Mark Visited Avoid duplicates BFS Levels: (0,0) d=0 (0,1) d=1 Queue processes by distance Level 0 --> Level 1 --> ... FINAL RESULT 1 2 Order of traversal Output: [[0,0], [0,1]] Cells sorted by distance: [0,0] dist=0 (first) [0,1] dist=1 (second) OK - Sorted! Key Insight: BFS naturally explores cells in order of their distance from the starting point. Each level of BFS corresponds to cells at the same Manhattan distance. This guarantees the result is sorted without explicit sorting, achieving O(rows * cols) time complexity. TutorialsPoint - Matrix Cells in Distance Order | BFS Approach
Asked in
Google 45 Amazon 32 Facebook 28
34.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen