蛇形矩阵
package com.zhanggaosong;
/**
* 蛇形矩阵
* @author zhanggaosong
*
*/
public class Main {
public static void main(String[] args) {
int i,j,k=1;
int n=6;
int a[][]=new int[100][100];
//上三角
for (i = 0; i <= n; i++) {
for (j = 0; j <= i; j++) {
if (i % 2 != 0) {
a[i - j][j] = k;
} else {
a[j][i - j] = k;
}
k++;
}
}
//下三角
for (i = n ; i < 2 * n; i++){
for (j = 0; j < 2 * n - i; j++) {
if (i % 2 != 0)
a[i-n+j+1][n-j] = k;
else
a[n - j][i-n+j+1] = k;
k++;
}
}
for(i=0;i<=n;i++){
for(j=0;j<=n;j++){
if(a[i][j]<10){
System.out.print(" "+a[i][j]+" ");
}else{
System.out.print(a[i][j]+" ");
}
}
System.out.println();
}
}
}
结果 :