难度: m i d d l e \color{orange}{middle} middle
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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 < = m a t r i x . l e n g t h < = 100 0 <= matrix.length <= 100 0<=matrix.length<=100
- 0 < = m a t r i x [ i ] . l e n g t h < = 100 0 <= matrix[i].length <= 100 0<=matrix[i].length<=100
注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/
算法
(暴力枚举) O ( n 2 ) O(n^2) O(n2)
可以将矩阵看成若干层,首先打印最外层的元素,其次打印次外层的元素,直到打印最内层的元素。
定义矩阵的第 k 层是到最近边界距离为 k 的所有顶点。例如,下图矩阵最外层元素都是第 1 层,次外层元素都是第 2 层,剩下的元素都是第 3 层。
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left),右下角位于 (bottom,right),按照如下顺序遍历当前层的元素。
从左到右遍历上侧元素,依次为 (top,left) 到 (top,right)。
从上到下遍历右侧元素,依次为 (top+1,right) 到 (bottom,right)。
如果 left<right 且 top<bottom,则从右到左遍历下侧元素,依次为 (bottom,right−1) 到 (bottom,left+1),以及从下到上遍历左侧元素,依次为 (bottom,left) 到 (top+1,left)。
遍历完当前层的元素之后,将 left 和 top 分别增加 1,将 right 和 bottom 分别减少 1,进入下一层继续遍历,直到遍历完所有元素为止。
复杂度分析
-
时间复杂度: O ( n ) O(n) O(n)
-
空间复杂度 : O ( 1 ) O(1) O(1) 除了输出数组以外,空间复杂度是常数。
C++ 代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int n = matrix.size(), m = matrix[0].size();
int left = 0, right = m - 1;
int top = 0,bottom = n - 1;
vector<int> res;
while (true) {
for (int i = left; i <= right; i ++) res.push_back(matrix[top][i]);
top ++;
if (top > bottom) break;
for (int i = top; i <= bottom; i ++) res.push_back(matrix[i][right]);
right --;
if (right < left) break;
for (int i = right; i >= left; i --) res.push_back(matrix[bottom][i]);
bottom --;
if (bottom < top) break;
for (int i = bottom; i >= top; i --) res.push_back(matrix[i][left]);
left ++;
if (left > right) break;
}
return res;
}
};