题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
import java.util.ArrayList;
public class Solution {
private static ArrayList<Integer> list = new ArrayList<Integer>();
int count = 0;
public ArrayList<Integer> printMatrix(int [][] matrix) {
list.clear();
if(matrix == null || matrix.length==0 || matrix[0].length ==0){
return list;
}
int x = 0;
int y = 0;
count = matrix.length * matrix[0].length;
while(list.size() < count){
printSingleCircle(x,y,matrix);
if(x+1 <= matrix.length-x-1-1){
x++;
}
if(y+1 <= matrix[0].length-y-1-1){
y++;
}
}
return list;
}
public void printSingleCircle(int x, int y, int[][] matrix){
int x1 = x;
int y1 = y;
int x2 = matrix.length - x1 - 1;
int y2 = matrix[0].length - y1 - 1;
for(int i=y1;i<=y2;i++){
if(list.size()<count)
list.add(matrix[x1][i]);
else
return;
}
for(int i=x1+1;i<=x2;i++){
if(list.size()<count)
list.add(matrix[i][y2]);
else
return;
}
for(int i=y2-1;i>=y1;i--){
if(list.size()<count)
list.add(matrix[x2][i]);
else
return;
}
for(int i=x2-1;i>=x1+1;i--){
if(list.size()<count)
list.add(matrix[i][y1]);
else
return;
}
}
}