《剑指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
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
vector<int> ans;
if(m == 0)return ans;
int n = matrix[0].size();
int up = 0,down = m-1,left=0,right=n-1,i,j=0;
ans.resize(m*n);
while(true)
{
for(i = left;i <= right; ++i)
ans[j++] = matrix[up][i];
if(++up>down)break;
for(i = up; i <= down; ++i)
ans[j++] = matrix[i][right];
if(--right<left)break;
for(i = right; i >= left;--i)
ans[j++] = matrix[down][i];
if(--down<up)break;
for(i = down; i>= up; --i)
ans[j++] = matrix[i][left];
if(++left>right)break;
}
return ans;
}
};
结果:
执行用时 :16 ms, 在所有 C++ 提交中击败了63.70%的用户
内存消耗 :9.5 MB, 在所有 C++ 提交中击败了100.00%的用户