打卡 DAY 7 螺旋矩阵 II

该文章描述了一种解决力扣(LeetCode)原题的方法,通过绕半径(n/2)圈并采用顺时针填充数组的策略。作者在实现过程中遇到了输出只有]的问题,发现原因是未正确使用模板代码中的参数。解决方案是理解和利用returnSize及returnColumnSizes来记录输出数组的行数和每行的列数。最终给出了完整的C语言代码实现。
摘要由CSDN通过智能技术生成

力扣原题链接

思路:绕(n / 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** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
    //returnSize拿来干啥的?是用来告诉主函数要输出的数组有多少行的,不然不设置就只输出“]”
    * returnSize = n;//用来记录输出数组有多少行
    * returnColumnSizes = (int *)malloc(sizeof(int) * n);//这个也是有用的!!记录输出数组每行有多少列,这里先动态分配内存出n行
    int num = 2;//num拿来记各个值,直到n^2
    int** res = (int **)malloc(sizeof(int *) * n);//malloc一个输出数组
    for(int i = 0; i < n; i ++){//给每个res[i]动态分配内存
    res[i] = (int *)malloc(sizeof(int) * n);
    (* returnColumnSizes)[i] = n;//每行多少列
    }
    int loop = n / 2;//loop是需要循环的圈数
    res[0][0] = 1;
    int x = 0;
    int y = 0;
    int distance = 2;//设置偏离值
    //int right = n - 1;//每一圈y的临界值
    while(loop){//当圈数不等于零时
        while(y <= n - distance){//向右赋值
        res[x][++ y] = num ++;
        }
        while(x <= n - distance){//向下赋值
        res[++ x][y] = num ++;
        }
        while(y > distance - 2){//向左赋值
        res[x][-- y] = num ++;
        }
        while(x > distance - 1){//向上赋值
        res[-- x][y] = num ++;
        }
        distance ++;
        loop --;
    }
    if(n % 2 && n != 1){//如果n为奇数时,需要往最中间填入一个数,若n = 1则跳过判断,不然输出数组[[2]],正确的是[[1]].
    res[n / 2][n / 2] = num;
    }
    return res;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值