剑指offer(19)顺时针打印出矩阵的元素
package OfferTest;
//顺时针打印矩阵
import java.util.ArrayList;
public class NoNineth {
public static ArrayList<Integer> printMatrix(int[][] matrix){
ArrayList<Integer> list = new ArrayList<Integer>();
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;//坐标比长度少一
int dC = matrix[0].length - 1;//下标比长度少一
while(tR <= dR && tC <= dC){
if(tR == dR){
for(int i = tC; i <= dC; i++){
list.add(matrix[tR][i]);
}
}else if(tC == dC){
for(int i = tR;i <= dR;i++){
list.add(matrix[i][tC]);
}
}else{
int curR = tR;
int curC = tC;
while(curC != dC){
list.add(matrix[tR][curC]);
curC++;
}
while(curR != dR){
list.add(matrix[curR][dC]);
curR++;
}
while(curC != tC){
list.add(matrix[dR][curC]);
curC--;
}
while(curR != tR){
list.add(matrix[curR][tC]);
curR--;
}
}
tR++;tC++;dR--;dC--;
}
return list;
}
public static void main(String[] args){
int[][] matrix= new int[4][4];
matrix[0] = new int[]{1,2,3,4};
matrix[1] = new int[]{5,6,7,8};
matrix[2] = new int[]{9,10,11,12};
matrix[3] = new int[]{13,14,15,16};
for(int i = 0;i < matrix.length;i++){
System.out.println();
for(int j = 0;j < matrix[0].length;j++){
System.out.print(matrix[i][j]+" ");
}
}
ArrayList<Integer> list = printMatrix(matrix);
System.out.println();
System.out.println("顺时针打印出的结果是:");
System.out.println(list);
}
}