zoukankan      html  css  js  c++  java
  • 二维数组问题

    找到数字的移动规律大致就能解决此题。
    每次循环开始时,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();
            }
        }
    }
  • 相关阅读:
    柯西恒等式 FPGA中信号的跨时钟域处理模板(二)
    OSPF
    Windows多网卡路由设置
    使用线程时需要注意的地方
    dicom 影像通信(scu、scp)的c-echo、c-store、c-find、c-move
    关于python3没有numpy和matplotlib库怎么办
    使用centos6.5时的几个小问题
    关于用Apache Beam跑WordCount
    MarkdownPad2的安装、破解和汉化
    安装Photoshop CS64
  • 原文地址:https://www.cnblogs.com/jzl123/p/12205953.html
Copyright © 2011-2022 走看看