题解 | #蛇形矩阵#
蛇形矩阵
http://www.nowcoder.com/practice/f228a074c5274619b26be544962375e1
import java.util.Scanner;
// 查看备注即可
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
int[][] a = new int[n][n];
int count = 1; // 数组的值
int x = 0;
int y = 0;
a[0][0] = 1;
// for (int k = 0; k < 3; k++) {
while (count < n * n) {
if (y < n - 1) {
y++;
// 向右赋值 x不变 y变
if (a[x][y] == 0) {
a[x][y] = ++count;
}
// System.out.println("向右赋值:" + count + ":" + x + "," + y);
} else {
// 向下赋值
x++;
if (a[x][y] == 0) {
a[x][y] = ++count;
}
// System.out.println("向下赋值:" + count + ":" + x + "," + y);
}
// 向左下角赋值
if (x < n - 1 && y > 0) {
int numy = y;
int numx = x;
for (int i = 0; i < Math.abs(numx - numy); i++) {
x++;
y--;
if (a[x][y] == 0) {
a[x][y] = ++count;
}
// System.out.println("向左下角赋值:" + count + ":" + x + "," + y);
}
}
if (x < n - 1) {
// 向下赋值
x++;
if (a[x][y] == 0) {
a[x][y] = ++count;
}
// System.out.println("向下赋值:" + count + ":" + x + "," + y);
} else {
y++;
// 向右赋值 x不变 y变
if (a[x][y] == 0) {
a[x][y] = ++count;
}
// System.out.println("向右赋值:" + count + ":" + x + "," + y);
}
// 右上角赋值
if (x > 0 && y < n - 1) {
int numy = y;
int numx = x;
for (int i = 0; i < Math.abs(numx - numy); i++) {
x--;
y++;
if (a[x][y] == 0) {
a[x][y] = ++count;
}
// System.out.println("右上角赋值:" + count + ":" + x + "," + y);
}
}
}
// 打印出数组
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}