题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> v;
if(matrix.empty()||matrix[0].empty())
return v;
int rows = matrix.size();
int cols = matrix[0].size();
int left = 0, top = 0, right = cols - 1, bottom = rows - 1;
while(left<=right && top <= bottom)
{
for(int i=left;i<=right;++i)
v.push_back(matrix[top][i]);
for(int j=top+1;j<=bottom;++j)
v.push_back(matrix[j][right]);
if (top != bottom)
for(int i=right-1;i>=left;--i)
v.push_back(matrix[bottom][i]);
if (left != right)
for(int j=bottom-1;j>top;--j)
v.push_back(matrix[j][left]);
left++,top++,right--,bottom--;
}
return v;
}
};