File: matrix-cells-in-distance-order/solution.py

Date: 2026-06-06

Time: 17:31

Purpose

This file solves LeetCode 1030 — Matrix Cells in Distance Order. Given an rows x cols matrix and a center cell (rCenter, cCenter), it returns every cell coordinate sorted by ascending Manhattan distance from the center.

Key Components

Solution.allCellsDistOrder

Contract: Given matrix dimensions and a center point, returns list[list[int]] of all [row, col] pairs ordered by Manhattan distance from (rCenter, cCenter). Ties in distance are broken by BFS discovery order (which is stable but not unique — any tie-breaking is valid per the problem spec).

Patterns

BFS as implicit sort. Rather than generating all cells and sorting by distance (O(n log n)), this uses breadth-first search from the center cell. BFS naturally visits nodes in order of hop count, and since each hop moves exactly one step in a cardinal direction, hop count equals Manhattan distance. This turns a sorting problem into a graph traversal.

The pattern is standard grid BFS:

Dependencies

Imports: collections.deque — used for the BFS queue.

Imported by: The test_solution.py in the same directory. The long "Imported By" list in the prompt is an artifact of the test harness structure — those are unrelated test files, not actual consumers of this module.

Flow

1. Initialize an empty result list, a visited grid (all False), and seed the BFS queue with (rCenter, cCenter).

2. Mark the center as visited.

3. While the queue is non-empty:

4. Return result.

Every cell is enqueued and dequeued exactly once, so the loop terminates after rows * cols iterations.

Invariants

Error Handling

None. The function assumes valid inputs per LeetCode constraints (0 <= rCenter < rows, 0 <= cCenter < cols, both positive). No bounds checking on the center coordinate or defensive handling for empty matrices.

Complexity

This is optimal since the output itself is O(rows × cols).

Topics to Explore

Beliefs