import java.util.ArrayList; public class Solution { static ArrayList resultList = new ArrayList<>();
public ArrayList<Integer> printMatrix(int [][] matrix) {
//tr为leftTop点的横坐标,tc为leftTop点的纵坐标
//dr为rightBottom点的横坐标,dc为rightBottom点的纵坐标
int tr = 0;
int tc = 0;
int dr = matrix.length - 1;
int dc = matrix[0].length - 1;
//每次都将最外层边界按顺序加入resultList
while(tr <= dr && tc <= dc){
getEdge(matrix, tr++, tc++, dr--, dc--);
}
return resultList;
}
public static ArrayList<Integer> getEdge(int[][] matrix, int tr, int tc, int dr, int dc){
//特殊情况1:leftTop点与rightBottom点处于同一行
if(tr == dr){
for(int i = tc; i <= dc; i++){
resultList.add(matrix[tr][i]);
}
}
//特殊情况2:leftTop点与rightBottom点处于同一列
else if(tc == dc){
for(int i = tr; i <= dr; i++){
resultList.add(matrix[i][tc]);
}
}
//正常情况:按照顺序添加即可
else {
int curR = tr;
int curC = tc;
while(curC != dc){
resultList.add(matrix[curR][curC]);
curC++;
}
while(curR != dr){
resultList.add(matrix[curR][curC]);
curR++;
}
while(curC != tc){
resultList.add(matrix[curR][curC]);
curC--;
}
while(curR != tr){
resultList.add(matrix[curR][curC]);
curR--;
}
}
return resultList;
}
}