leetcode 链接:顺时针打印矩阵
此题同:
[中等] 54. 螺旋矩阵
题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例:
输入: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]
解答 & 代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int rows = matrix.size();
if(rows == 0)
return result;
int cols = matrix[0].size();
if(cols == 0)
return result;
// 左、右、上、下边界
int left = 0, right = cols - 1, up = 0, down = rows - 1;
while(left <= right && up <= down)
{
// 遍历上边界
for(int col = left; col <= right; ++col)
result.push_back(matrix[up][col]);
++up; // 上边界下移
if(up > down)
break;
// 遍历右边界
for(int row = up; row <= down; ++row)
result.push_back(matrix[row][right]);
--right; // 右边界左移
if(right < left)
break;
// 遍历下边界
for(int col = right; col >= left; --col)
result.push_back(matrix[down][col]);
--down; // 下边界上移
if(down < up)
break;
// 遍历左边界
for(int row = down; row >= up; --row)
result.push_back(matrix[row][left]);
++left; // 左边界右移
if(left > right)
break;
}
return result;
}
};
执行结果:
执行结果:通过
执行用时:4 ms, 在所有 C++ 提交中击败了 99.67% 的用户
内存消耗:9.6 MB, 在所有 C++ 提交中击败了 72.01% 的用户
