-
Notifications
You must be signed in to change notification settings - Fork 0
/
printMatrix
54 lines (50 loc) · 908 Bytes
/
printMatrix
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
54
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
int row = matrix.size();
int col = matrix[0].size();
vector<int> res;
if (row == 0 || col == 0)
{
return res;
}
int left = 0;
int top = 0;
int right = col - 1;
int down = row - 1;
while (left <= right&&top <= down)
{
//从左上到右上
for (int i = left; i <= right; i++)
{
res.push_back(matrix[top][i]);
}
//从右上到右下
for (int i = top + 1; i <= down; i++)
{
res.push_back(matrix[i][right]);
}
//从右下到左下
if (top != down)
{
for (int i = right - 1; i >= left; i--)
{
res.push_back(matrix[down][i]);
}
}
//从左下到左上
if (left != right)
{
for (int i = down - 1; i>top; i--)
{
res.push_back(matrix[i][left]);
}
}
left++;
top++;
right--;
down--;
}
return res;
}
};