|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +We are given a matrix with R rows and C columns has cells with integer |
| 4 | +coordinates (r, c), where 0 <= r < R and 0 <= c < C. |
| 5 | +
|
| 6 | +Additionally, we are given a cell in that matrix with coordinates (r0, c0). |
| 7 | +
|
| 8 | +Return the coordinates of all cells in the matrix, sorted by their distance from |
| 9 | +(r0, c0) from smallest distance to largest distance. Here, the distance between |
| 10 | +two cells (r1, c1) and (r2, c2) is the Manhattan distance, |r1 - r2| + |c1 - c2|. |
| 11 | +(You may return the answer in any order that satisfies this condition.) |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: R = 1, C = 2, r0 = 0, c0 = 0 |
| 15 | +Output: [[0,0],[0,1]] |
| 16 | +Explanation: The distances from (r0, c0) to other cells are: [0,1] |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: R = 2, C = 2, r0 = 0, c0 = 1 |
| 20 | +Output: [[0,1],[0,0],[1,1],[1,0]] |
| 21 | +Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2] |
| 22 | +The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. |
| 23 | +
|
| 24 | +Example 3: |
| 25 | +Input: R = 2, C = 3, r0 = 1, c0 = 2 |
| 26 | +Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] |
| 27 | +Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3] |
| 28 | +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]]. |
| 29 | +
|
| 30 | +Note: |
| 31 | +
|
| 32 | +1 <= R <= 100 |
| 33 | +1 <= C <= 100 |
| 34 | +0 <= r0 < R |
| 35 | +0 <= c0 < C |
| 36 | +""" |
| 37 | +from typing import List |
| 38 | + |
| 39 | + |
| 40 | +class Solution: |
| 41 | + def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: |
| 42 | + """ |
| 43 | + bucket sort |
| 44 | + """ |
| 45 | + r_max = max(r0, R-1 - r0) |
| 46 | + c_max = max(c0, C-1 - c0) |
| 47 | + lst = [[] for _ in range(r_max + c_max + 1)] |
| 48 | + for i in range(R): |
| 49 | + for j in range(C): |
| 50 | + lst[abs(i - r0) + abs(j - c0)].append([i, j]) |
| 51 | + |
| 52 | + ret = [] |
| 53 | + for e in lst: |
| 54 | + ret.extend(e) |
| 55 | + |
| 56 | + return ret |
0 commit comments