#1030
Matrix Cells in Distance Order
EasyArrayMathGeometrySortingMatrixLayered generationSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the fact that we can generate coordinates based on their distance in layers. Instead of sorting after calculating all distances, we can directly generate the cells in order of their distance from the center.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty list to store cell coordinates.
- 2Step 2: Use a loop to iterate over possible distances from 0 up to the maximum possible distance.
- 3Step 3: For each distance, calculate the cells that are at that distance from the center and add them to the list.
- 4Step 4: Return the list of coordinates.
solution.py14 lines
1# Full working Python code
2from typing import List
3
4def all_cells_dist_order(rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
5 result = []
6 for d in range(rows + cols):
7 for r in range(max(0, rCenter - d), min(rows, rCenter + d + 1)):
8 c1 = cCenter - (d - abs(r - rCenter))
9 c2 = cCenter + (d - abs(r - rCenter))
10 if 0 <= c1 < cols:
11 result.append([r, c1])
12 if 0 <= c2 < cols and c1 != c2:
13 result.append([r, c2])
14 return resultℹ
Complexity note: The time complexity is O(n) because we are generating cells based on their distance without needing to sort them afterward. Each cell is processed once, leading to linear complexity.
- 1Understanding Manhattan distance is crucial for this problem.
- 2Generating coordinates in layers helps avoid unnecessary sorting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.