题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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:
void PrintMatrix(vector<int>& res,int r,int c,int s,vector<vector<int> > matrix)
{
int i = 0, j = 0, k = 0, m = 0, p = 0;
int endX=c-1-s; // 每圈最右边的边界
int endY=r-1-s; // 每圈最下方的边界
for (j = s; j<=endX; j++) // 打印每圈最上面的一行
res.push_back(matrix[s][j]);
if(s<endY) //打印每圈最右边一列
{
for (k = s + 1; k<=endY; k++)
res.push_back(matrix[k][endX]);
}
if(s<endY && s<endX) // 打印每圈最下方一行
{
for (m = endX-1; m >= s; --m)
res.push_back(matrix[endY][m]);
}
if(s<endX && s<endY-1) //打印每圈最左边一列
{
for (p = endY-1; p>s; --p)
res.push_back(matrix[p][s]);
}
}
vector<int> printMatrix(vector<vector<int> > matrix) {
int row=matrix.size();
int column=matrix[0].size();
int start=0;
vector<int> res;
while(row>2*start && column>2*start)
{
PrintMatrix(res,row,column,start,matrix);
++start;
}
return res;
}
};