题目描述
从键盘输入一个整数(1~20)
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
解法1(参考顺时针打印矩阵):
public class test{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("输入一个数字"); int num = scanner.nextInt(); // 行和列都是num int cols = num; int rows = num; // 创建二维数组 int[][] arr = new int[rows][cols]; // 初始化边界 int c1 = 0, c2 = cols - 1; int r1 = 0, r2 = rows - 1; // 计算打几圈,奇数需要加1圈 int times = (Math.min(cols,rows) & 1) == 0 ? Math.min(cols,rows) / 2 : Math.min(cols,rows) / 2 + 1; int n = 1; // 需要赋值的数 for (int time = 0; time < times; time++) { // 右 for (int i = c1; i <= c2; i++) arr[r1][i] = n++; // 下 for (int i = r1 + 1; i <= r2; i++) arr[i][c2] = n++; // 考虑边界,例如最后一圈只有一行(r1=r2),只有一列(c1=c2);如果不加限制,会重复向左打印或者重复向上打印 if (c1 != c2 && r1 != r2){ // 左 for (int i = c2 - 1; i >= c1; i--) arr[r2][i] = n++; // 上 for (int i = r2 - 1; i > r1; i--) arr[i][c1] = n++; } c1++; c2--; r1++; r2--; } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
解法2(参考康师傅,与解法1相比,不需要计算圈数!!!)
public class test{ public static void main(String[] args) { int n = 7; int[][] arr = new int[n][n]; int count = 0; // 需要赋值的数 int c1 = 0, c2 = n - 1; int r1 = 0, r2 = n - 1; while (c1 <= c2){ for (int i = c1; i <= c2; i++) arr[r1][i] = ++count; for (int i = r1 + 1; i <= r2; i++) arr[i][c2] = ++count; for (int i = c2 - 1; i >= c1 ; i--) arr[r2][i] = ++count; for (int i = r2 - 1; i > r1; i--) arr[i][c1] = ++count; c1++; c2--; r1++; r2--; } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }