Problem
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)
.
Return _the coordinates of all cells in the matrix, sorted by theirdistance 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|
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= rows, cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols
Solution
Method 1 – Sorting by Manhattan Distance
Intuition
The Manhattan distance between two cells is the sum of the absolute differences of their row and column indices. We can generate all cell coordinates and sort them by their distance to the center cell.
Approach
- Generate all cell coordinates
(r, c)
for the matrix. - For each cell, compute its Manhattan distance to
(rCenter, cCenter)
. - Sort the list of coordinates by this distance.
- Return the sorted list.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(mn log(mn))
, wherem
andn
are the matrix dimensions, for sorting all cells. - 🧺 Space complexity:
O(mn)
, for storing all cell coordinates.