题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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> result; //保存矩阵输出顺序
int rows = matrix.size(); //矩阵行数
int cols = matrix[0].size(); //矩阵列数
int start = 0; //圈数
while (rows > start * 2 && cols > start * 2) //满足循环,打印一圈
{
int endX = cols - 1 - start; //每一圈的中止行号
int endY = rows - 1 - start; //每一圈的中止列号
for (int i = start; i <= endX; i++) //从左至右打印一行
{
result.push_back(matrix[start][i]);
}
if (start < endY) //中止行号大于起始行号
{
for (int i = start + 1; i <= endY; i++) //从上到下打印一列
{
result.push_back(matrix[i][endX]);
}
}
if (start < endX && start < endY) //中止行号大于起始行号且中止列号大于起始列号
{
for (int i = endX-1; i >= start; i--) //从右到左打印一行
{
result.push_back(matrix[endY][i]);
}
}
if (start <endX && start <endY-1) //中止行号大于起始行号且中止列号至少起始列号大2
{
for (int i = endY-1; i >= start + 1; i--) //从下到上打印一列
{
result.push_back(matrix[i][start]);
}
}
start++;
}
return result;
}
};