题目描述
输入整数N,输出一个N阶的回字形二维数组。
数组的最外层为1,次外层为2,以此类推。
分析
我们发现每个二维矩阵(1和0除外),长宽相同的矩阵,我们可以利用蛇形矩阵 的方法规定上下左右四个方向,并且当我们每次走 right
这个方向的时候,我们都让count++,最终就得到了数据
代码实现
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
// 输入一个数
boolean flag = true;
while (flag) {
int n = sc.nextInt();
if(n ==0){ sc.close(); break;};
// System.out.println();
if (n == 1) System.out.println(1);
else {
int[][] w = new int[n][n];
// 计数器
int count = 0;
// 定义边界。
int left = 0, right = w[0].length - 1, top = 0, bottom = w.length - 1;
// 规定一个方向
String dir = "right";
while (left <= right && top <= bottom) {
if (dir == "right") {
count++;
for (int i = left; i <= right; i++) {
w[top][i] = count;
// count++;
}
top++;
dir = "down";
} else if (dir == "down") {
for (int i = top; i <= bottom; i++) {
w[i][right] = count;
}
right--;
dir = "left";
} else if (dir == "left") {
for (int i = right; i >= left; i--) {
w[bottom][i] = count;
}
bottom--;
dir = "top";
} else if (dir == "top") {
for (int i = bottom; i >= top; i--) {
w[i][left] = count;
}
left++;
dir = "right";
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%d ", w[i][j]);
}
System.out.println("");
}
}
System.out.println("");
}
}
}