Leetcode #1030: Matrix Cells in Distance Order
In this guide, we solve Leetcode #1030 Matrix Cells in Distance Order in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Geometry, Array, Math, Matrix, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0
Output: [[0,0],[0,1]]
Explanation: The distances from (0, 0) to other cells are: [0,1]
Python Solution
class Solution:
def allCellsDistOrder(
self, rows: int, cols: int, rCenter: int, cCenter: int
) -> List[List[int]]:
q = deque([[rCenter, cCenter]])
vis = [[False] * cols for _ in range(rows)]
vis[rCenter][cCenter] = True
ans = []
while q:
for _ in range(len(q)):
p = q.popleft()
ans.append(p)
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = p[0] + a, p[1] + b
if 0 <= x < rows and 0 <= y < cols and not vis[x][y]:
vis[x][y] = True
q.append([x, y])
return ans
Complexity
The time complexity is O(n log n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.