题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
解题思路:
打印一圈可以分为4步:1)从左到右打印 2)从上到下打印 3)从右到左打印 4)从下到上打印
我们可以控制每一圈的四个顶点处的坐标,然后来进行循环。需要注意的是如果只有一行的话,是指需要第一步从左往右打印而不需要从右往左打印的。
具体是实现见下列代码:
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
if (matrix.empty() || matrix[0].empty())
return res;
int row = matrix.size(), col = matrix[0].size();
int left = 0, right = col - 1, top = 0, bottom = row - 1; //边界信息
while (left <= right&&top <= bottom)
{
for (int i = left; i <= right; i++) //从左向右
res.push_back(matrix[top][i]);
for (int j = top + 1; j <= bottom; j++) //从上到下
res.push_back(matrix[j][right]);
if (top != bottom) //如果只有一行的话,就不需要从到左了,需要进行判断
for (int i = right - 1; i >= left; i--)
res.push_back(matrix[bottom][i]);
if (left != right) //如果只要一列,同样不在需要从下到上了,一定要进行判断
for (int j = bottom - 1; j > top; j--) //这边必须是j>top而不是j>=top,否则,把左上角的数值多输出一次
res.push_back(matrix[j][left]);
left++, top++, right--, bottom--; //每次循环之后更新4个边界
}
return res;
}
};