正方形二维矩阵从内向外打印和从外向内打印
选取左上和右下两个点循环往外扩张或者向内收缩打印。
public static void main(String[] args) {
int[][] a = {
{1, 2, 3,11},
{4, 5, 6,12},
{7, 8, 9,13},
{17, 18, 19,14},
};
int[][] b = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("由内往外");
soutInner(a);
System.out.println("-------------");
soutInner(b);
System.out.println("由外往内");
soutOuter(a);
System.out.println("-------------");
soutOuter(b);
}
public static void soutOuter(int [][] a){
int lur=0;
int luc=0;
int rdr=a.length-1;
int rdc=a.length-1;
for (;rdr>=lur;luc++,lur++,rdc--,rdr--){
soutOuter(a,luc,lur,rdc,rdr);
}
}
public static void soutOuter(int[][] a ,int luc,int lur,int rdc,int rdr){
if (luc==rdr){
System.out.println(a[luc][lur]);
}else {
for (int i=luc; i<rdc ; i++) {
System.out.print(a[lur][i]);
System.out.print(",");
}
System.out.println();
for (int i=lur; i<rdr ; i++) {
System.out.print(a[i][rdc]);
System.out.print(",");
}
System.out.println();
for (int i =rdc; i>luc ; i--) {
System.out.print(a[rdr][i]);
System.out.print(",");
}
System.out.println();
for (int i=rdr; i>lur ; i--) {
System.out.print(a[i][luc]);
System.out.print(",");
}
System.out.println();
}
}
public static void soutInner(int [][] a){
int lur=(a.length-1)/2;
int luc=(a.length-1)/2;
int rdr=a.length/2;
int rdc=a.length/2;
for (;lur>=0;luc--,lur--,rdc++,rdr++){
soutInner(a,luc,lur,rdc,rdr);
}
}
public static void soutInner(int[][] a ,int luc,int lur,int rdc,int rdr){
if (luc==rdr){
System.out.println(a[luc][lur]);
}else {
// 从右下开始,向上打印,列column不变,行row减少
for (int i=rdr-1; i>=lur ; i--) {
System.out.print(a[i][rdc]);
System.out.print(",");
}
System.out.println();
// 从右上开始,向左打印,行row不变,列column减少
for (int i=rdr-1; i>=lur ; i--) {
System.out.print(a[lur][i]);
System.out.print(",");
}
System.out.println();
// 从左上开始,向下打印,列column不变,行row增加
for (int i =lur+1; i<=rdr ; i++) {
System.out.print(a[i][luc]);
System.out.print(",");
}
System.out.println();
// 从左下开始,向右打印,行row不变,列column增加
for (int i=luc+1; i<=rdc ; i++) {
System.out.print(a[rdr][i]);
System.out.print(",");
}
System.out.println();
}
}