从键盘输入一个整数(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,1+4(n-1),1+4*2*(n-2),……
根据n确定可把该二维数组划分成多少环,也就是说,第一环的第一个元素为1,第二环的第一个元素为1+4(n-1),……
写算法,先确定第一环的算法,写在一个方法中,让该方法同时适应第二环,第三环,……
源代码如下:
package com.lzw.cnum;
public class CirNum { int[][] num = null; int circle = 0; int n = 0; public CirNum(int n) { super(); this.n = n; this.num = new int[n][n]; } // 当输入的n>1时,用该方法填充第一环。 public void lauchRect(int index, int first) { // 对参数的注释,first表示左上角的第一个元素。index左上角元素的下标值(即第(index+1)环)。 this.circle = (n + 1) / 2; int i = index, j = index; // 处理最第一行。 for (; j < n - 1 - index; j++) { // 之所以减去index是因为把内环又当成新环用。 this.num[i][j] = first + j - index; } // 处理最后一列。 for (; i < n - 1 - index; i++) { this.num[i][j] = first + (n - 1 - 2 * index) + i - index; } // 处理最后一行。 for (; j - index > 0; j--) { this.num[i][j] = first + 2 * (n - 1 - 2 * index) + (n - j - 1) - index; } // 处理第一列。 for (; i - index > 0; i--) { this.num[i][j] = first + 3 * (n - 1 - 2 * index) + (n - i - 1) - index; } //如果n是奇数,确定该矩阵中中间元素。 if (n % 2 != 0) { this.num[(n - 1) / 2][(n - 1) / 2] = n * n; } // 递归。 if (index < this.circle) { index++; System.out.println("index= " + index); this.lauchRect(index, 1 + index * 4 * (n - index)); } } public void display(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(this.num[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { int flag = 4;// 设置输入的数字。 CirNum cir = new CirNum(flag); cir.lauchRect(0, 1); cir.display(flag); } }