一个关于递归的算法。

 

从键盘输入一个整数(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); } }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值