首页 > 其他 > 详细

leetcode-螺旋矩阵(指针)

时间:2021-06-04 22:20:00      阅读:15      评论:0      收藏:0      [点我收藏+]

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

技术分享图片
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

技术分享图片
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int *spiralOrder(int **matrix, int matrixSize, int *matrixColSize, int *returnSize)
{

    int rows = matrixSize, columns = matrixColSize[0];
    int total = rows * columns;
    int *order = malloc(sizeof(int) * total);
    *returnSize = 0;
//  对变量进行抽象,可大大减小指针操作复杂度
    int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
    while (left <= right && top <= bottom)
    {
        for (int column = left; column <= right; column++)
        {
            order[(*returnSize)++] = *(*(matrix + top) + column);
            printf("%d\n", *(*(matrix + top) + column));
        }

        for (int row = top + 1; row <= bottom; row++)
        {
            order[(*returnSize)++] = *(*(matrix + row) + right);
            printf("%d\n", *(*(matrix + row) + right));
        }
        if (left < right && top < bottom)
        {
            for (int column = right - 1; column > left; column--)
            {
                order[(*returnSize)++] = *(*(matrix + bottom) + column);
               
            }

            for (int row = bottom; row > top ; row--)
            {
                order[(*returnSize)++] = *(*(matrix + row) + left);
               
            }
        }
        left++;
        right--;
        top++;
        bottom--;
    }
    return order;
}

leetcode-螺旋矩阵(指针)

原文:https://www.cnblogs.com/yangtai/p/14851188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!