顺时针打印矩阵
题目描述
| 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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 {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
if((matrix==null||matrix.length==0)||(matrix.length==1&&matrix[0].length==0)){
return list;
}
int slength=matrix.length<=matrix[0].length?matrix.length:matrix[0].length;
int a=slength%2==0?slength/2:(slength/2+1);
int count=0;
while(count<a){
int i=1;
int j=0;
while(j<matrix[0].length-2*count){
list.add(matrix[count][j+count]);
j++;
}
if(matrix.length-2*count==1){
return list;
}
while(i<=matrix.length-2-2*count){
list.add(matrix[i+count][j-1+count]);
i++;
}
while(--j>=0){
list.add(matrix[i+count][j+count]);
}
while(--i>0&&(matrix[0].length-2*count!=1)){
list.add(matrix[i+count][count]);
}
count++;
}
return list;
}
}