[ 题目描述 ]:
[ 思路 ]:
- 题目要求按顺时针顺序给出m行n列的矩阵的数组
- 按照题目所给的顺序挨个插入答案数组中
- 运行如下
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {*returnSize = matrixSize * matrixColSize[0];int* ans = (int*)malloc(sizeof(int) * (*returnSize)); int top = 0, bottom = matrixSize - 1;int left = 0, right = matrixColSize[0] - 1;int index = 0;int direction = 0;while (top <= bottom && left <= right) {if (direction == 0) {for (int i = left; i <= right; i++) {ans[index++] = matrix[top][i];}top++;} else if (direction == 1) {for (int i = top; i <= bottom; i++) {ans[index++] = matrix[i][right];}right--;} else if (direction == 2) {for (int i = right; i >= left; i--) {ans[index++] = matrix[bottom][i];}bottom--;} else if (direction == 3) {for (int i = bottom; i >= top; i--) {ans[index++] = matrix[i][left];}left++;}direction = (direction + 1) % 4;}return ans;
}
- 时间复杂度O(mn),空间复杂度O(mn)
[ 官方题解 ]:
- 一、模拟,思路基本同上
- 二、按层模拟,可以将矩阵看成若干层,首先输出最外层的元素,其次输出次外层的元素,直到输出最内层的元素