题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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
输入
[[1,2],[3,4]]
返回值
[1,2,4,3]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> result;
int cols = matrix[0].size();
int rows = matrix.size()-1;
int startCol = 0;
int startRow = 0;
if(rows < 0 && cols == 0)
return result;
if(cols==1)
{
for(int i= 0;i<=rows;i++)
result.push_back(matrix[i][0]);
return result;
}
if(rows==0)
{
for(int i= 0;i<cols;i++)
result.push_back(matrix[0][i]);
return result;
}
while(cols-startCol>0&&rows-startRow>=0)
{
for(int i = startCol;i<cols;i++)
{
result.push_back(matrix[startRow][i]);
}
for(int i = startRow+1;i<rows;i++)
{
result.push_back(matrix[i][cols-1]);
}
if(rows-startRow>0)
for(int i = cols-1;i>=startCol;i--)
{
result.push_back(matrix[rows][i]);
}
if(cols-startCol>1)
for(int i = rows-1;i>startRow;i--)
{
result.push_back(matrix[i][startCol]);
}
startCol++;
startRow++;
cols = cols-1;
rows = rows-1;
}
return result;
}
};
|