- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintMatrix.java
More file actions
Latest commit
58 lines (42 loc) · 1.71 KB
/
Copy pathPrintMatrix.java
File metadata and controls
58 lines (42 loc) · 1.71 KB
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
importjava.util.ArrayList;
publicclassPrintMatrix {
publicstaticvoidmain(String[] args) {
int[][] matrix = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}};
System.out.println(newPrintMatrix().printMatrix(matrix));
}
publicArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> res = newArrayList<>();
if (matrix.length <= 0) returnres;
intleft = 0;
intright = matrix[0].length-1;
inttop = 0;
intbottom = matrix.length-1;
if (right == 0 && bottom == 0) {
res.add(matrix[0][0]);
returnres;
}
if (right == 0) {
for(inti = top; i <= bottom; i++) res.add(matrix[i][right]); // right
returnres;
}
// System.out.println(left + " " + right + " " + top + " " + bottom);
while(left < right && top < bottom) { // 外圈嵌套
// 循环一圈
for(inti = left; i < right; i++) res.add(matrix[top][i]); // top
for(inti = top; i < bottom; i++) res.add(matrix[i][right]); // right
for(inti = right; i > left; i--) res.add(matrix[bottom][i]); //bottom
for(inti = bottom; i > top; i--) res.add(matrix[i][left]);// left
left++;
right--;
top++;
bottom--;
}
//System.out.println(left + " " + right + " " + top + " " + bottom);
if (left == right) {
for(inti = top; i <= bottom; i++) res.add(matrix[i][left]); // right
} elseif (top == bottom) {
for(inti = left; i <= right; i++) res.add(matrix[top][i]); // top
}
returnres;
}
}