顺时针打印矩阵

时间:2023-02-11 09:25:59

顺时针打印矩阵
顺时针打印矩阵

分析:

顺时针打印矩阵

顺时针打印矩阵

特殊情况处理

顺时针打印矩阵

顺时针打印矩阵

代码:

package arrays20;

public class Demo01 {

public static void ClockwisePrintMatrix(int[][] arrays,int columns,int rows){
if(arrays==null || columns<=0 || rows<=0){
return;
}
int start = 0;
while(columns>start*2 && rows>start*2){
CirclePrintMatrix(arrays,columns,rows,start);
start++;
}
}

public static void CirclePrintMatrix(int[][] arrays,int columns,int rows,int start){
int endX = columns-1-start;
int endY = rows-1-start;

//从左到右打印一行
for (int i = start; i <= endX; i++) {
int number = arrays[start][i];
System.out.print(number+" ");
}

//从上到下打印一行
if(start<endY){
for (int i = start+1; i <= endY; i++) {
int number = arrays[i][endX];
System.out.print(number+" ");
}
}


//从右到左打印一行
if (start<endX && start<endY) {
for (int i = endX-1; i >= start; i--) {
int number = arrays[endY][i];
System.out.print(number+" ");
}
}

//从下到上打印一行(至少三行两列)
if (start<endX && start<endY-1) {
for (int i = endY-1; i >= start+1; i--) {
int number = arrays[i][start];
System.out.print(number+" ");
}
}
}

public static void main(String[] args) {
int[][] arrays = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
//System.out.println(arrays.length+","+arrays[0].length);
// 列 行
ClockwisePrintMatrix(arrays,arrays[0].length,arrays.length);
}
}

运行结果:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10