-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolutionJZ19.java
More file actions
52 lines (49 loc) · 1.4 KB
/
SolutionJZ19.java
File metadata and controls
52 lines (49 loc) · 1.4 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
package com.company;
import java.util.ArrayList;
public class SolutionJZ19 {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> arrayList=new ArrayList<>();
if(matrix==null||matrix.length==0||matrix[0].length==0)
return arrayList;
//定义四个值up,down,left,right
int up,down,left,right;
up=0;
down=matrix.length-1;
left=0;
right=matrix[0].length-1;
while(true){
//最上面一行
for(int col=left;col<=right;col++){
arrayList.add(matrix[up][col]);
}
//向下逼近
up++;
if(up>down)
break;
//最右面一行
for(int row=up;row<=down;row++){
arrayList.add(matrix[row][right]);
}
//向左逼近
right--;
if(left>right)
break;
//最下面一行
for(int col=right;col>=left;col--){
arrayList.add(matrix[down][col]);
}
//向上逼近
down--;
if(up>down)
break;
for(int row=down;row>=up;row--){
arrayList.add(matrix[row][left]);
}
//向右逼近
left++;
if(left>right)
break;
}
return arrayList;
}
}