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();
            }
        }
    }
  • 相关阅读:
    用GDB调试程序(一)
    关于“鸡脚神”的看法
    Oracle 经典SQL 专为笔试准备
    怎样设计接口?
    myeclipse6.0下载及注冊码
    VB连接Mysql数据库
    开源html5_kiwijs_helloworld
    server宕机监控、检測、报警程序(139绑定手机短信报警)monitor_down.sh
    js实现自己定义鼠标右键-------Day45
    C/C++程序猿必须熟练应用的开源项目
  • 原文地址:https://www.cnblogs.com/jzl123/p/12205953.html
Copyright © 2011-2022 走看看