距离顺序排列矩阵单元格
Matrix Cells in Distance Order
解
在返回数组的基础上再开一列,储存曼哈顿距离
/**
* 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 comp(const void *a, const void *b)
{
int **c = (int **)a;
int **d = (int **)b;
return (*c)[2] - (*d)[2];
}
int** allCellsDistOrder(int R, int C, int r0, int c0, int* returnSize, int** returnColumnSizes)
{
int i, j, order = 0;
int **ret;
int S = R * C;
ret = (int **)malloc(S * sizeof(int *));
for (i = 0; i < S; i++){
ret[i] = (int *)calloc(3, sizeof(int));
}
*returnColumnSizes = (int *)calloc(S, sizeof(int));
for (i = 0; i < S; i++){
(*returnColumnSizes)[i] = 2;
}
for (i = 0; i < C; i++){
for (j = 0; j < R; j++){
ret[order][0] = j;
ret[order][1] = i;
ret[order][2] = abs(r0 - j) + abs(c0 - i);
//printf("%d ", ret[order][2]);
order++;
}
}
qsort(ret, S, sizeof(int *), comp);
*returnSize = S;
return ret;
}
结果