leetcode1030

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.)

把距离都算出来,枚举距离输出即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] f = new int[R][C];
int[][] s = new int[R*C][2];
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
f[i][j] = Math.abs(r0-i)+Math.abs(c0-j);

int max = R+C;
int l = 0;
for(int k=0;k<max;k++)
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
if (f[i][j]==k){
s[l][0] = i;
s[l][1] =j;
l++;
}
return s;
}
}