LeetCode-1030. Matrix Cells in Distance Order(距离顺序排列矩阵单元格)

本文介绍了一种算法,用于将矩阵中的单元格按照与指定点的曼哈顿距离进行排序。通过创建一个额外的列来存储每个单元格到指定点的距离,然后使用qsort函数对所有单元格进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

距离顺序排列矩阵单元格

在这里插入图片描述

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;

}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值