题解 | #回型矩阵#
回型矩阵
http://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343
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 = 0; // 数组的值
int x = 0;
int y = 0;
while (count < n * n) {
// 上面一层赋值 x不变y变
for (int j = 0; j < n; j++) {
if (a[x][j] == 0) {
a[x][j] = ++count;
y = j;
}
}
// 右面赋值 x变 y不变
for (int i = 0 ; i < n; i++) {
if (a[i][y] == 0) {
a[i][y] = ++count;
x = i;
}
}
// 下面赋值 x不变y变
for (int j = n - 1; j >= 0; j--) {
if (a[x][j] == 0) {
a[x][j] = ++count;
y = j;
}
}
// 左面赋值 x变 y不变
for (int i = n - 1 ; i >= 0; i--) {
if (a[i][y] == 0) {
a[i][y] = ++count;
x = i;
}
}
}
// 打印出数组
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();
}
}
}