Matrix Cells in Distance Order LeetCode solution in Python

1
class Solution:
2
def allCellsDistOrder(
3
self, rows: int, cols: int, rCenter: int, cCenter: int
4
) -> List[List[int]]:
5
# create a r, c matrix given the rows & cols
6
# each element represents a list [r, c] where r is the row & c the col
7
# find find the distances of all cells from the center (append to res)
8
# sort the result by distance function
9
# Time O(M + N) Space O(M + N)
10

11
def distance(p1, p2):
12
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
13

14
matrix = [[i, j] for i in range(rows) for j in range(cols)]
15
center = [rCenter, cCenter]
16
matrix.sort(key=lambda c: distance(c, center))
17

18
return matrix

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0