29.顺时针打印矩阵 (Easy)*
题目描述*
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例*
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
输入: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
代码*
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.size() == 0 || matrix[0].size() == 0) {
return res;
}
int targetLength = matrix.size() * matrix[0].size();
int rowTop = 0, rowBottom = matrix.size() - 1, colLeft = 0, colRight = matrix[0].size() - 1;
while(rowTop <= rowBottom && colLeft <= colRight) {
for(int i = colLeft; i <= colRight; i++) {
res.push_back(matrix[rowTop][i]);
}
for(int i = rowTop + 1; i <= rowBottom; i++) {
res.push_back(matrix[i][colRight]);
}
if(rowBottom != rowTop) {
for(int i = colRight - 1; i >= colLeft; i--) {
res.push_back(matrix[rowBottom][i]);
}
}
if(colLeft != colRight) {
for(int i = rowBottom - 1; i > rowTop; i--) {
res.push_back(matrix[i][colLeft]);
}
}
colLeft++, colRight--, rowTop++, rowBottom--;
}
return res;
}
};
最后更新: July 23, 2022