思路:
声明矩阵list;
返回按曼哈顿距离排序的list;
1 class Solution(object): 2 3 def allCellsDistOrder2(self, R, C, r0, c0): 4 """ 5 :type R: int 6 :type C: int 7 :type r0: int 8 :type c0: int 9 :rtype: List[List[int]] 10 """ 11 dist = [[i, j] for i in range(R) for j in range(C)] 12 dist.sort(key=lambda x: abs(x[0] - r0) + abs(x[1] - c0)) 13 return dist 14 15 def allCellsDistOrder(self, R, C, r0, c0): 16 """ 17 :type R: int 18 :type C: int 19 :type r0: int 20 :type c0: int 21 :rtype: List[List[int]] 22 """ 23 # 返回值 24 dist_list = [[] for i in range(200)] 25 # print(dist_list) 26 # 计算距离并排序 27 for i in range(R): 28 for j in range(C): 29 distinct = abs(r0 - i) + abs(c0 - j) 30 # 将坐标插入距离对应的dist_list下标处 31 dist_list[distinct].append([i, j]) 32 result = [] 33 # 遍历dist_list,不为空则添加到result中 34 for i in dist_list: 35 if i: 36 result.extend(i) 37 else: 38 break 39 return result 40 41 42 if __name__ == '__main__': 43 solution = Solution() 44 print(solution.allCellsDistOrder(R=1, C=2, r0=0, c0=0))