二维数组问题

找到数字的移动规律大致就能解决此题。
每次循环开始时,i为奇数时向下移动i,向左移动i,再向下移动1;i为偶数时,向右移动i,向上移动i,再向右移动1。最后判断为最后一层时,不向下也不向上移动

/**
 * @author :jizhaolun
 * @date :Created in 2020/1/17 14:33
 * @description:
 * @modified By:
 * @version: $
 *
 *
 */
public class PrintNum {

    /**
     *
     * @param n 需要输出数组的层数
     * @return
     */
    private static int[][] initArray(int n) {
        int[][] array = new int[n][n];

        array[0][0] = 1;
        array[0][1] = 2;

        int nextX=1;
        int nextY=0;

        int num = 2;

        for (int i = 1; i < n; i++) {
            // 每次循环开始时,i为奇数时向下移动i,向左移动i,再向下移动1;i为偶数时,向右移动i,向上移动i,再向右移动1。最后判断为最后一层时,不向下也不向上移动
            if (i % 2 != 0) {
                for (int j = 0; j < i; j++) {
                    nextY++;
                    array[nextY][nextX] = ++num;
                }
                for (int j = 0; j < i; j++) {
                    nextX--;
                    array[nextY][nextX] = ++num;
                }
                if (i != n-1) {
                    nextY++;
                    array[nextY][nextX] = ++num;
                }
            } else {
                for (int j = 0; j < i; j++) {
                    nextX++;
                    array[nextY][nextX] = ++num;
                }
                for (int j = 0; j < i; j++) {
                    nextY--;
                    array[nextY][nextX] = ++num;
                }
                if (i != n-1) {
                    nextX++;
                    array[nextY][nextX] = ++num;
                }
            }
        }

        return array;
    }
    public static void main(String[] args) {
        int[][] ints = initArray(5);
        for (int[] anInt : ints) {
            for (int i : anInt) {
                System.out.print(i+"	");
            }
            System.out.println();
        }
    }
}
原文地址:https://www.cnblogs.com/jzl123/p/12205953.html