剑指Offer(Java版)第二十四题:顺时针打印矩阵

/*
顺时针打印矩阵
*/
public class Class24 {

public void printMatrix(int[][] matrix){
if(matrix == null || matrix.length <= 0){
return;
}else{
printMatrixCircle(matrix,0);
}
}
//index代表一个控制符,来控制打印的范围
public void printMatrixCircle(int[][] matrix,int index){
int row = matrix.length;
int col = matrix[0].length;
int endX = col - index - 1;
int endY = row - index - 1;
if(endX < index || endY < index){
return;
}
//仅一列
if(endX == index){
for(int i = index; i <= endY; i++){
System.out.print(matrix[i][index] + " ");
}
return;
}
//仅一行
if(endY == index){
for(int i = index; i <= endX; i++){
System.out.print(matrix[index][i] + " ");
}
return;
}
//开始打印边界
//步骤一
for(int i = index; i <= endX; i++){
System.out.print(matrix[index][i] + " ");
}
//步骤二
for(int i = index + 1; i <= endY; i++){
System.out.print(matrix[i][endX] + " ");
}
//步骤三
for(int i = endX - 1; i >= index; i--){
System.out.print(matrix[endY][i] + " ");
}
//步骤四
for(int i = endY - 1; i >= index + 1; i--){
System.out.print(matrix[i][index] + " ");
}
printMatrixCircle(matrix,index + 1);
}

public void test(int[][] matrix){
printMatrix(matrix);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Class24 c = new Class24();
int[][] a = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
c.printMatrix(a);
}

}

posted on 2020-03-16 21:53  桌子哥  阅读(124)  评论(0编辑  收藏  举报