如果输入如下矩阵: 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 class Testa {
static int LINE =16;
static int COLUMN= 16;
static int[] DATA= new int[LINE*COLUMN];
static {
for(int i=0;i<LINE*COLUMN;i++) {
DATA[i]=i+1;
}
}
public static void main(String[] args) {
int ax=COLUMN / 2;
if (LINE % 2 == 0 && COLUMN % 2 == 0 && LINE == COLUMN) {
for (int inx = 0; inx <ax; inx++) {
int []data=calNum(inx);
for (int i = 0; i < COLUMN; i++) {
System.out.println(data[i]);
}
for (int j = 1; j < LINE; j++) {
System.out.println(data[j*LINE+COLUMN -1]);
}
for (int k = COLUMN-2; k >-1; k--) {
System.out.println( data[(LINE-1)*LINE+k]);
}
for (int n = LINE-2; n >0; n--) {
System.out.println( data[n*LINE]);
}
}
}
}
private static int[] calNum(int inx) {
if(inx==0) {return DATA;}
LINE = LINE -2;
COLUMN = COLUMN -2;
int len = LINE*COLUMN;
int[] data = new int[len];
// System.out.println(inx +" "+Arrays.toString(DATA));
for (int i = 0; i < len; i++) {
int lie = i % LINE;
int hang = i / LINE;
int datali=(int) Math.sqrt(DATA.length);
data[i] = DATA[(hang + 1) * (datali) + lie+1];
}
DATA = Arrays.copyOf(data, len);
return data;
}
}