题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
解题思路
依次从左到右、从上到下、从右到左、从下到上对二维数组进行遍历,因此可以设置四条边界,通过边界的调整控制遍历的路径,从而实现从外向里顺时针打印每个数字。
代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
if((matrix == NULL) || (matrixSize == 0))
{
*returnSize = 0;
return NULL;
}
*returnSize = matrixSize * matrixColSize[0];
int *res = calloc(*returnSize, sizeof(int));
int row = 0, col = 0;
int index = 0;
int uprow = 0;
int bottomrow = matrixSize - 1;
int leftCol = 0;
int rightCol = matrixColSize[0] - 1;
while(index < (*returnSize))
{
row = uprow;
for (col = leftCol; (index < (*returnSize)) && (col <= rightCol); col++)
{
res[index] = matrix[row][col];
index++;
}
uprow++;
col = rightCol;
for (row = uprow; ((index < (*returnSize)) && (row <= bottomrow)); row++)
{
res[index] = matrix[row][col];
index++;
}
rightCol--;
row = bottomrow;
for (col = rightCol; ((index < (*returnSize)) && (col >= leftCol)); col--)
{
res[index] = matrix[row][col];
index++;
}
bottomrow--;
col = leftCol;
for (row = bottomrow; ((index < (*returnSize)) && (row >= uprow)); row--)
{
res[index] = matrix[row][col];
index++;
}
leftCol++;
}
return res;
}
执行结果
时间复杂度:O(mn),空间复杂度:O(1)。