leetcode刷题 1030.距离顺序排列矩阵单元格
思路
1.按照顺序构建二维数组
2.构造排序规则即可
代码
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int R0, C0;
int cmp(void* _a, void* _b) {
int *a = *(int**)_a, *b = *(int**)_b;
return fabs(a[0] - R0) + fabs(a[1] - C0) - fabs(b[0] - R0) - fabs(b[1] - C0);
}
int** allCellsDistOrder(int R, int C, int r0, int c0, int* returnSize, int** returnColumnSizes) {
R0 = r0, C0 = c0;
int** ret = malloc(sizeof(int*) * R * C);
*returnColumnSizes = malloc(sizeof(int) * R * C);
for (int i = 0; i < R * C; i++) {
(*returnColumnSizes)[i] = 2;
ret[i] = malloc(sizeof(int) * 2);
}
*returnSize = 0;
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
ret[*returnSize][0] = i;
ret[*returnSize][1] = j;
(*returnSize)++;
}
}
qsort(ret, R * C, sizeof(int*), cmp);
return ret;
}