[LeetCode]#1030. Matrix Cells in Distance Order
2 min readJan 28, 2021
Environment: Python 3.8
Key technique: sort, append
We are given a matrix with R
rows and C
columns has cells with integer coordinates (r, c)
, where 0 <= r < R
and 0 <= c < C
.
Additionally, we are given a cell in that matrix with coordinates (r0, c0)
.
Return the coordinates of all cells in the matrix, sorted by their distance from (r0, c0)
from smallest distance to largest distance. Here, the distance between two cells (r1, c1)
and (r2, c2)
is the Manhattan distance, |r1 - r2| + |c1 - c2|
. (You may return the answer in any order that satisfies this condition.)
Example 1:
Input: R = 1, C = 2, r0 = 0, c0 = 0
Output: [[0,0],[0,1]]
Explanation: The distances from (r0, c0) to other cells are: [0,1]
Analysis:
- Calculate distance and related coordinate.
- Sort it.
- Return it based on distance.
Solution:
class Solution:
def allCellsDistOrder(self, R, C, r0, c0):
tmp=[]
ans=[]
for i in range(R):
for j in range(C):
tmp.append((abs(r0 - i) + abs(c0 - j), [i, j]))
tmp.sort()
for i in range(len(tmp)):
ans.append(tmp[i][1])
return ans
Submissions: