Given the integers R
and C
representing the number of rows and columns in a matrix, and the integers r0
and c0
representing the coordinates of a starting cell (r0, c0)
, return the matrix cells in distance order from (r0, c0)
. The cells are ordered by their Manhattan distance, which is defined as:
[ \text{Manhattan Distance} = | r1 - r0 | + | c1 - c0 | ] |
(r0, c0)
be outside the boundary of the matrix?
(r0, c0)
will always be within the boundary of the matrix.(r0, c0)
.R
and C
?
R
and C
are within standard problem limits (0 ≤ R, C ≤ 100).(r, c)
from the starting cell (r0, c0)
.def allCellsDistOrder(R, C, r0, c0):
# Step 1: Generate all coordinates in the matrix
cells = [(r, c) for r in range(R) for c in range(C)]
# Step 2: Define a function to calculate Manhattan distance
def manhattanDist(cell):
r, c = cell
return abs(r - r0) + abs(c - c0)
# Step 3: Sort the list of cells based on their Manhattan distance
cells.sort(key=manhattanDist)
# Step 4: Return the sorted list of coordinates
return cells
# Example usage:
R, C, r0, c0 = 2, 3, 1, 2
print(allCellsDistOrder(R, C, r0, c0))
The time complexity of this solution is as follows:
Therefore, the overall time complexity is:
[ \mathbf{O(R \cdot C) + O((R \cdot C) \log (R \cdot C))} = \mathbf{O((R \cdot C) \log (R \cdot C))} ]
This is efficient for the input size constraints typically expected in such problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?