思路简介:
先输出外圈 然后逐步缩圈
而每个输出圈的操作又是相同的,我们可以将其放在一个循环当中
先进行输出最上边---最右边---最下边---最左边
然后进行缩圈【将左上端点 右下端点的值进行改变】
注意此处每次最外层循环对辅助变量x,y的初始化的操作!!
下文代码当中也进行了具体的展示:
public class Main {
/*按照顺时针的顺序来进行输出
* 回形取数
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16
*
* 结果示例:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
*/
public static void main(String[] args) {
int[][] mat=new int[][] {
{1,2,3,4,66},
{5,6,7,8,77},
{9,10,11,12,88},
{13,14,15,16,99}
};
//思路:1.先取外圈,然后内圈
//2.外圈先从最上边 最右边 最下边 最左边
//3.逐渐向内圈聚拢
int leftupX=0,leftupY=0,rightdownX=mat[0].length-1,rightdownY=mat.length-1;
/*
* 每进行一次最外循环完成了一圈的打印
* 我们接下来要进行缩圈
*/
while(leftupX<=rightdownX&&leftupY<=rightdownY) {
int x=leftupX,y=leftupY;
//最上边
while(x<=rightdownX) {
System.out.print(mat[y][x++]+" ");
}
/*
* 遇到while结束之后一定要注意其循环退出的条件
*此时x=rightdownX+1
*则要现将x进行恢复
*/
x=rightdownX;
y++;
//最右边
while(y<=rightdownY) {
System.out.print(mat[y++][x]+" ");
}
/*
*此时退出循环:yx=rightdownY+1
*则要现将y进行恢复
*/
y=rightdownY;
x--;
//最下边
while(x>=leftupX) {
System.out.print(mat[y][x--]+" ");
}
/*
*此时退出循环:x=-1
*则要现将x进行恢复
*/
x=leftupX;
y--;
//最左边
while(y>leftupY) {
System.out.print(mat[y--][x]+" ");
}
/*
*此时退出循环:y=0
*无需进行恢复 因为进行缩圈之后重新进行初始化先x,y
*/
/*
* 此时完成了一圈的打印
* 我们接下来要进行缩圈
* 我们又可以观察到每一圈的打印步骤是重复的,考虑将其放在一个循环当中
*/
//缩圈
leftupX++;
leftupY++;
rightdownX--;
rightdownY--;
}
}
}