/**
* 输出n*n的矩阵
* 1 2 6
* 3 5 7
* 4 8 9
*(0,0);(0,1)(1,0);(2,0)(1,1)(0,2);(1,2)(2,1)(2,2)
*看成/这种倾斜方向的斜对角线
* @author trq
*
*/
public class outMatrix {
public static void main(String[] args) {
outmatrix(matrix(5));
}
public static int[][] matrix(int n) {
int count = 0;
int value = 0;
int row, collum = n;
int i = 0, j = 0;
int[][] number = new int[n][n];
while (count <= 2 * (n - 1)) {
for (; i + j == count && count % 2 == 0;) {//偶數
if (i == 0 && j == 0) {//坐标(0,0)开始,默认往右走
number[i][j] = ++value;
j++;
count++;
break;
} else if (i < n - 1 && j == n - 1) {//最右一列时,往下走
i++;
count++;
break;
} else if (i == 0 && j <= n - 1) { //最上面一列时,往右走
j++;
count++;
break;
} else {
do {
number[i][j] = ++value;
i--;
j++;
} while (i < n && j < n && i >= 0 && j >= 0);
i++;
j--;
if (i == n - 1 && j == n - 1)
return number;
}
}
for (; i + j == count && count % 2 != 0;) {//奇数
if (i == n - 1 && j < n - 1) {//最下面一行时,往右走
j++;
count++;
break;
} else if ( i <= n - 1 &&j == 0) {//最左一列时,往下走
i++;
count++;
break;
} else {
do {
number[i][j] = ++value;
i++;
j--;
} while (i < n && j < n && i >= 0 && j >= 0);
i--;
j++;
if (i == n - 1 && j == n - 1)
return number;
// count++;
}
}
}
return number;
}
public static void outmatrix(int[][] number) {
for (int i = 0; i < number.length; i++) {
for (int j = 0; j < number[0].length; j++) {
System.out.print(number[i][j] + " ");
}
System.out.println();
}
}
}