1.设置四个变量,左,右,上,下 来记录当前打印到哪个边界
2外循环里包裹从右到左,从上到下,从右到左,从下到上,四个子循环
3.外循环继续的条件是 (up <= down && left <= right)
4.可能是坑:
当数组是{1,2,3,4}(就是行数是单数的情况下)这样的时候,进入从右到左的时候(子循环3)需要先判断当前的down和up变量是否满足关系,不然就会打印和和本次从左到右重复的内容
同理,列数是单数的情况下,也需要在子循环4加判断条件
public static void printClockwise(int[][] array){
int left = 0 ;
int right = array[0].length - 1;
int up = 0;
int down = array.length - 1;
int index = 0;
while(right >= left && down >= up){
//子循环1,从左到右
index = left;
while(index <= right){
System.out.print(array[up][index] + " ");
index ++;
}
up++;
//子循环2,从上到下
index = up;
while(index <= down){
System.out.print(array[index][right] + " ");
index++;
}
right--;
//子循环3,从右到左,避免入坑,需要加这个判断条件防止打印出和从左到右一样的循环
if (up <= down) {
index = right;
while (index >= left) {
System.out.print(array[down][index] + " ");
index--;
}
down--;
}
//子循环4,同理,加判断语句
if (left <= right) {
index = down;
while (index >= up) {
System.out.print(array[index][left] + " ");
index--;
}
left++;
}
}
}