leetcode 2326 螺旋矩阵IV

1.题目要求 :

c 复制代码
给你两个整数:m 和 n ,表示矩阵的维数。

另给你一个整数链表的头节点 head 。

请你生成一个大小为 m x n 的螺旋矩阵,矩阵包含链表中的所有整数。链表中的整数从矩阵 左上角 开始、顺时针 按 螺旋 顺序填充。如果还存在剩余的空格,则用 -1 填充。

返回生成的矩阵。

2.题目代码:

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
/**
 * 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** spiralMatrix(int m, int n, struct ListNode* head, int* returnSize, int** returnColumnSizes) {
    //创造数组,存入链表结点值
    int* number = (int*)malloc(sizeof(int) * (m * n));
    int j = 0;
    struct ListNode* cur = head;
    //遍历链表,把链表的结点值存入数组中
    while(cur){
        number[j] = cur->val;
        j++;
        cur = cur->next;
    }
    //如果链表的结点数小于二维数组的元素数,后面补-1;
    while(j < (m * n)){
        number[j] = -1;
        j++;
    }
    int row = m;
    int col = n;
    int i = 0;
    //创造二维数组
    int** mat = (int**)malloc(sizeof(int*) * m);
    for(i = 0;i < m;i++){
        mat[i] = (int*)malloc(sizeof(int) * n);
    }
    i = 0;
    j = 0;
    int f = 0;
    //开始进行螺旋遍历
    while(f < (m * n)){
        int i1 = i;
        int j1 = j;
        while(j1 < col){
            mat[i1][j1] = number[f];
            f++;
            j1++;
        }
        if(f >= (m * n)){
            break;
        }
        j1--;
        i1++;
        while(i1 < row){
            mat[i1][j1] = number[f];
            f++;
            i1++;
        }
        if(f >= m * n){
            break;
        }
        i1--;
        j1--;
        while(j1 >= j){
            mat[i1][j1] = number[f];
            f++;
            j1--;
        }
        if(f >= m * n){
            break;
        }
        j1++;
        i1--;
        while(i1 > i){
            mat[i1][j1] = number[f];
            f++;
            i1--;
        }
        if(f >= m * n){
            break;
        }
        i++;
        j++;
        row--;
        col--;
    }
    //返回二维数组
    *returnSize = m;
    *returnColumnSizes = (int*)malloc(sizeof(int) * m);
    for(i = 0;i < m;i++){
        (*returnColumnSizes)[i] = n;
    }
    return mat;
}
相关推荐
东阳马生架构23 分钟前
Sentinel源码—8.限流算法和设计模式总结二
算法·设计模式·sentinel
老饼讲解-BP神经网络1 小时前
一篇入门之-评分卡变量分箱(卡方分箱、决策树分箱、KS分箱等)实操例子
算法·决策树·机器学习
何其有幸.1 小时前
实验6-3 使用函数求特殊a串数列和(PTA|C语言)
c语言·数据结构·算法
不会计算机的捞地1 小时前
【数据结构入门训练DAY-24】美国大选
数据结构·算法
明月看潮生2 小时前
青少年编程与数学 02-018 C++数据结构与算法 11课题、分治
c++·算法·青少年编程·编程与数学
Echo``2 小时前
2:QT联合HALCON编程—图像显示放大缩小
开发语言·c++·图像处理·qt·算法
.似水2 小时前
2025.4.22_C_可变参数列表
java·c语言·算法
Felven3 小时前
A. Ideal Generator
java·数据结构·算法
MoonBit月兔3 小时前
双周报Vol.70: 运算符重载语义变化、String API 改动、IDE Markdown 格式支持优化...多项更新升级!
ide·算法·哈希算法
How_doyou_do3 小时前
树状数组底层逻辑探讨 / 模版代码-P3374-P3368
数据结构·算法·树状数组