题目链接:剑指 Offer 29. 顺时针打印矩阵
题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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
注意:本题与主站 54. 螺旋矩阵相同,关于54题的解法在力扣:54. 螺旋矩阵这篇博客里。
思路和算法:
可以将矩阵看成若干层,首先打印最外层的元素,其次打印次外层的元素,直到打印最内层的元素。
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于(top,left)
,右下角位于 (bottom,right)
,按照如下顺序遍历当前层的元素。
(1)从左到右遍历上侧元素,依次为(top,left)
到(top,right)
;
(2)从上到下遍历右侧元素,依次为(top+1,right)
到 (bottom,right)
;
如果 left<right 且top<bottom,则
(3)从右到左遍历下侧元素,依次为(bottom,right−1)
到(bottom,left+1)
;
(4)从下到上遍历左侧元素,依次为(bottom,left)
到 (top+1,left)
。
遍历完当前层的元素之后,将 left 和 top 分别增加 1,将right 和 bottom 分别减少 1,进入下一层继续遍历,直到遍历完所有元素为止。
代码(c++):
//按层模拟
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (!matrix.size() || !matrix[0].size()) return {};
vector<int> res;
int rows = matrix.size(); //最外层行数
int columns = matrix[0].size(); //最外层列数
int top = 0, left = 0, bottom = rows - 1, right = columns - 1; //左上角:[top, left] 右下角:[bottom, right]
while (left <= right && top <= bottom) {
//遍历top行:left --> right
for (int column = left; column <= right; ++column) {
res.push_back(matrix[top][column]);
}
//遍历right列:top+1 --> bottom
for (int row = top + 1; row <= bottom; ++row) {
res.push_back(matrix[row][right]);
}
//判断是否已经到了最里层
if (left < right && top < bottom) {
//遍历bottom行:right-1 --> left+1
for (int column = right - 1; column > left; --column) {
res.push_back(matrix[bottom][column]);
}
//遍历left列:bottom --> top+1
for (int row = bottom; row > top; --row) {
res.push_back(matrix[row][left]);
}
}
top++;
left++;
bottom--;
right--;
}
return res;
}
};