打印zigzag矩阵

比较愚蠢但是很好理解的一种方法

public static void printZigzag (int n){
int[][] arr = new int[n][];
//动态创建数组 并初始化
for (int i = 0; i < arr.length; i ++)
{
arr[i] = new int[n];
Arrays.fill(arr[i], 0);
} int num = 0, flag = 0;
int row = 0, col = 0;
//处理 左上三角阵
for (row = 0; row < arr.length; row ++)
{
col = 0;
// 偶数行
if(row%2==0){
num = row*(row+1)/2;
flag=1;
}
// 奇数行
if(row%2==1)
{
num = row*(row+1)/2 + row;
flag=-1;
}
for(int i = 0; i < row+1; i++)
{
arr[row-i][col+i] = num + i*flag;
} } // 同理 处理右下三角阵
for (row = 0; row < arr.length - 1; row ++)
{
int newRow = n-1-row;
int newCol = n-1; //偶数行
if(row%2==0){
num = n*n-1 - (row*(row+1)/2);
flag = -1;
}
//奇数行
if(row%2==1){
num = n*n-1 - (row*(row+1)/2) - row;
flag = 1;
} for(int i = 0; i < row+1; i++)
{
arr[newRow+i][newCol-i] = num + i*flag;
}
} for (int[] a : arr) {
for (int i : a) {
System.out.printf("%3d", i);
}
System.out.println();
} }

  

上一篇:Java整型与字符串相互转换(转)


下一篇:项目Alpha冲刺Day12