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;
}
相关推荐
TracyCoder1234 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u0109272715 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_941837265 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义6 小时前
java基础十二
java·数据结构·算法
四维碎片6 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs6 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E7 小时前
【优先级队列】主持人调度(二)
算法
weixin_445476687 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王7 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区8 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展