顺时针打印矩阵,求代码优化啊
public class 顺时针打印矩阵 {
/**
* @param args
*/
public void print(int[][]arr, int rows, int cols){
if(arr == null || rows < 1 || cols < 1){
return;
}
int start = 0;
while(start * 2 < rows && start * 2 < cols){
int endY = rows - 1 - start;
int endX = cols - 1 - start;
//从左向右打印上一层
for(int i = start; i <= endX; i++){
System.out.print(arr[start][i] + " ");
}
if(start < endY){
//从上往下打印右边一层
for(int i = start + 1; i <= endY; i++ ){
System.out.print(arr[i][endX]+" ");
}
}
if(start < endX && start < endY){
//从右向左打印下边一层
for(int i = endX - 1; i >= start; i--){
System.out.print(arr[endY][i]+" ");
}
}
if(start < endX && start < endY - 1){
//从下往上打印左边一层
for(int i = endY - 1; i >= start + 1; i--){
System.out.print(arr[i][start]+" ");
}
}
start++;
}
}
public static void main(String[] args) {
int[][] arr = {{1},{2},{3},{4},{5}};
顺时针打印矩阵 t = new 顺时针打印矩阵();
t.print(arr, 5, 1);
}
}
|
|