生成两数相乘结果的螺旋数组

来源:互联网 发布:淘宝退款退优惠卷吗 编辑:程序博客网 时间:2024/05/16 08:42

有人问到一个算法:

两数相乘,生成一个螺旋数组。举例说明:

3 * 4 生成的螺旋数组为:

1---2---3---4

10-11-12--5

9---8---7---6

5 * 6 生成的螺旋数组为:

1---2---3---4---5---6

18-19-20-21-22---7

17-28-29-30-23---8

16-27-26-25-24---9

15-14-13-12-11--10

也就是从外层顺时针向内层旋转;a * b的情况下,a为行数,b为列数。


分析过程:
以5 * 6为例,将生成二维数组 A[5][6],其横竖坐标分别用i和j来表示,则生成的螺旋数组:
从外向内第一圈(最外层):
1、上层:A[1][j],其中( j : 1-6 )
2、右层:A[i][6],其中( i : 2-5)
3、下层:A[5][j],其中( j : 5-1 )
4、左层:A[i][1],其中( i : 4-2)
从外向内第二圈:
1、上层:A[2][j],其中( j : 2-5 )
2、右层:A[i][5],其中( i : 3-4)
3、下层:A[4][j],其中( j : 4-2 )
4、左层:A[i][2],其中( i : 3-3)
。。。。。。

于是可写出如下算法:


public class ScrewArray {private int[][] screw(int a, int b) {int[][] array = new int[a][b];int i = 2;int j = 1;int layer = 1;int counter = 1;int end = a * b;boolean done = false;out:while (!done) {// 上层j = layer;while (j <= (b - layer + 1)) {array[layer - 1][j - 1] = counter++;// System.out.println("1: " + array[layer - 1][j - 1]);if (counter > end) {done = true;break out;}j++;}j--;// 右层i = layer + 1;while (i <= (a - layer + 1)) {array[i - 1][b - layer + 1 - 1] = counter++;// System.out.println("2: " + array[i - 1][b - layer + 1 - 1]);if (counter > end) {done = true;break out;}i++;}i--;// 下层j = b - layer;while (j >= layer) {array[a - layer + 1 - 1][j - 1] = counter++;// System.out.println("3: " + array[a - layer + 1 - 1][j - 1]);if (counter > end) {done = true;break out;}j--;}j++;// 左层i = a - layer;while (i >= layer + 1) {array[i - 1][layer - 1] = counter++;// System.out.println("4: " + array[i - 1][layer - 1]);if (counter > end) {done = true;break out;}i--;}i++;layer++;}return array;}public static void main(String[] args) {int[][] result = new ScrewArray().screw(5, 6);for (int i = 0; i < result.length; i++) {for (int j = 0; j < result[i].length; j++) {System.out.print(result[i][j] + "  ");}System.out.println();}}}


初步测试了一下,似乎结果都是正确的。。。试试吧!

算法很不优雅,也难免会有错误,欢迎指正!

原创粉丝点击