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;
}
相关推荐
gihigo199822 分钟前
Bezier曲线曲面生成算法
算法
平行侠1 小时前
024多精度大整数 - 突破硬件精度限制的任意精度运算
数据结构·算法
IronMurphy1 小时前
【算法四十五】139. 单词拆分
算法
洛水水2 小时前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
如竟没有火炬3 小时前
用队列实现栈
开发语言·数据结构·python·算法·leetcode·深度优先
云栖梦泽在4 小时前
AI安全入门:AI模型泄露的风险与防护措施
人工智能·算法·动态规划
水木流年追梦4 小时前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
洛水水4 小时前
【力扣100题】31.二叉树的层序遍历
算法·leetcode·职场和发展
君义_noip4 小时前
CSP-S 2025 入门级 第一轮(初赛) 完善程序(1)
c++·算法·信息学奥赛·初赛·csp 第一轮
洛水水4 小时前
【力扣100题】41.爬楼梯
算法·leetcode·职场和发展