题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 1213 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> res;
res.clear();
int rows = matrix.size();
int cols = matrix[0].size();
int circles = ((rows>cols?cols:rows)-1)/2 + 1;
for(int i=0; i<circles; i++){
int endx = rows-i-1;
int endy = cols-i-1;
//从左到右
for(int y=i; y<=endy; y++){
res.push_back(matrix[i][y]);
}
//从上到下 不包括matrix[i][endy]
for(int x=i+1; x<=endx; x++){
res.push_back(matrix[x][endy]);
}
//从右到左 不接受相同的一行的反向打印 不包括matrix[endx][endy]
if(i<endx){
for(int y=endy-1; y>=i;y--)
res.push_back(matrix[endx][y]);
}
//从下到上 不接受相同的一列的反向打印 不包括matrix[endx][i] 和matrix[i][i]
if(i<endy){
for(int x=endx-1;x>i;x--)
res.push_back(matrix[x][i]);
}
}
return res;
}
};
吐血版本1:
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
res.clear();
int rows = matrix.size();
int cols = matrix[0].size();
int circles = ((rows>cols?cols:rows) - 1)/2 + 1; //-1非常不错 优先级 加减大于位运算
//循环打印不同圈 起点是(i,i);
for(int i = 0; i < circles; i++)
{
int endX = cols - i - 1;
int endY = rows - i - 1;
//从左到右 一定执行
for(int j = i; j < endX + 1; j++)
res.push_back(matrix[i][j]);
//从上到下 一行时不执行
for(int j = i + 1; j < endY + 1; j++)
res.push_back(matrix[j][endX]);
//以下两部分一定要检查是否会重复打印 mark
//从右到左
for(int j = endX - 1; (j >= i)&&(i!=endY); j--)
res.push_back(matrix[endY][j]);
//从下到上
for(int j = endY - 1; (j >= i+1)&&(i!=endX); j--)
res.push_back(matrix[j][i]);
}
return res;
}
};