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.php
Additionally, we are given a cell in that matrix with coordinates (r0, c0).ios
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:less
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]
复制代码
Example 2:yii
Input: R = 2, C = 2, r0 = 0, c0 = 1
Output: [[0,1],[0,0],[1,1],[1,0]]
Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2]
The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.
复制代码
Example 3:svg
Input: R = 2, C = 3, r0 = 1, c0 = 2
Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3]
There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].
复制代码
Note:ui
1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C
复制代码
根据题意,就是计算矩阵中各个位置到 (r0, c0) 的曼哈顿距离,而后按照距离从小到大输出矩阵的索引。时间复杂度为 O(R * C),空间复杂度为 O(R * C)。this
class Solution(object):
def allCellsDistOrder(self, R, C, r0, c0):
"""
:type R: int
:type C: int
:type r0: int
:type c0: int
:rtype: List[List[int]]
"""
def dist(point):
pi, pj = point
return abs(pi - r0) + abs(pj - c0)
points = [(i, j) for i in range(R) for j in range(C)]
return sorted(points, key=dist)
复制代码
Runtime: 132 ms, faster than 98.52% of Python online submissions for Matrix Cells in Distance Order.
Memory Usage: 13.6 MB, less than 99.10% of Python online submissions for Matrix Cells in Distance Order.
复制代码
每日格言:逆境是达到真理的一条通路。es5