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;
}
相关推荐
野犬寒鸦1 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
霖霖总总1 小时前
[小技巧66]当自增主键耗尽:MySQL 主键溢出问题深度解析与雪花算法替代方案
mysql·算法
rainbow68891 小时前
深入解析C++STL:map与set底层奥秘
java·数据结构·算法
wangjialelele2 小时前
平衡二叉搜索树:AVL树和红黑树
java·c语言·开发语言·数据结构·c++·算法·深度优先
驱动探索者2 小时前
linux mailbox 学习
linux·学习·算法
ringking1232 小时前
autoware-1:安装环境cuda/cudnn/tensorRT库函数的判断
人工智能·算法·机器学习
大闲在人3 小时前
8. 供应链与制造过程术语:产能
算法·制造·供应链管理·智能制造·工业工程
一只小小的芙厨3 小时前
寒假集训笔记·以点为对象的树形DP
c++·算法
历程里程碑3 小时前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
执风挽^3 小时前
Python基础编程题2
开发语言·python·算法·visual studio code