题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
问题分析
- 将问题分解,实现顺时针打印主要分几个步骤
- 对于判断条件和边界条件要仔细分析
解题思路1
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> printResult ;
int rows = matrix.size();
int cols = matrix[0].size();
if(rows == 0 || cols == 0)
{
return printResult;
}
printResult.clear();
int left = 0;
int right = cols-1;
int bottom = rows-1;
int top = 0;
//分解遍历
while(left <= right && top <= bottom)
{
//自左到右
for (int i = left; i <= right; ++i)
{
printResult.push_back(matrix[top][i]);
}
//自上到下
for (int i = top+1; i <= bottom; ++i)
{
printResult.push_back(matrix[i][right]);
}
//自右向左,同时要判断left和right的大小
if(bottom != top)
{
for (int i = right-1; i >= left; --i)
{
printResult.push_back(matrix[bottom][i]);
}
}
//自下向上,同时要判断bottom和top的大小
if (right != left)
{
for(int i = bottom-1; i > top ; --i)
{
printResult.push_back(matrix[i][left]);
}
}
left++;
top++;
right--;
bottom--;
}
return printResult;
}
};
网友评论