forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
69 lines (64 loc) · 1.71 KB
/
Solution.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* @author mcrwayfun
* @version 1.0
* @description
* @date Created in 2019/1/2
*/
public class Solution {
/**
* 转圈打印矩阵
* @param matrix 矩阵
* @return 存放结果的list
*/
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> reList = new ArrayList<>();
if (matrix == null) {
return reList;
}
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
while (tR <= dR && tC <= dC) {
printMatrix(matrix, tR++, tC++, dR--, dC--, reList);
}
return reList;
}
public void printMatrix(int[][] matrix, int tR, int tC, int dR, int dC, ArrayList<Integer> reList) {
// 只有一行
if (tR == dR) {
for (int i = tC; i <= dC; i++) {
reList.add(matrix[tR][i]);
}
}
// 只有一列
else if (tC == dC) {
for (int i = tR; i <= dR; i++) {
reList.add(matrix[i][tC]);
}
} else {
int curR = tR;
int curC = tC;
// 从左到右
while (curC != dC) {
reList.add(matrix[tR][curC]);
curC++;
}
// 从上到下
while (curR != dR) {
reList.add(matrix[curR][dC]);
curR++;
}
// 从右到左
while (curC != tC) {
reList.add(matrix[dR][curC]);
curC--;
}
// 从下到上
while (curR != tR) {
reList.add(matrix[curR][tC]);
curR--;
}
}
}
}