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;
}
相关推荐
暖阳华笺6 分钟前
【高频考点】回溯(暴力搜索)
数据结构·c++·算法·回溯法
hunterkkk(c++)6 分钟前
学习dijkstra算法(c++)
c++·学习·算法
lightqjx15 分钟前
【算法】数据结构_单调队列
数据结构·算法·单调队列
小四季豆24 分钟前
《数据结构与算法》-顺序表:算法落地的第一个线性结构
c语言·数据结构·算法
8Qi831 分钟前
LeetCode 96:不同的二叉搜索树(Unique Binary Search Trees)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
1892280486132 分钟前
NV041固态MT29F16T08GSLCEM9-QBES:C
人工智能·算法·microsoft·缓存·性能优化
罗超驿1 小时前
15.LeetCode 30. 串联所有单词的子串(Java):滑动窗口+哈希表详解
算法·leetcode
Marianne Qiqi1 小时前
非hot100的力扣算法题
数据结构·算法·leetcode
CC数学建模1 小时前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
Dillon Dong1 小时前
【风电控制】双馈风机网侧高低穿控制策略——从VrtCal信号处理到状态机逻辑的完整解析
算法·变流器·风电控制·dfig