回型打印/遍历/赋值二维数组

此章节介绍了回环遍历或赋值二位数组的方法,如:

在这里插入图片描述

回环遍历的主要思想:

1,每一层的上右下左形成一个环,每一环进行遍历或赋值;
2,增加环的数值/深度,进行逐层遍历,直到遍历到中心数据;

下面是回环赋值的代码,同样可以用于回环遍历;

    import org.junit.Test;
    @Test
    public void test_cycle_print() {
        System.out.println("test_cycle_print start");
        int[][] array = new int[3][5];
        cyclePrint(array,3,5);
        printArray(array,3,5);
        System.out.println("test_cycle_print end");
    }
    
    void cyclePrint(int[][] array, int width, int height) {
        // 行列下标index;
        int i = 0, j = 0;
        // 每一环的计数;
        int cycle = 0;
        // 赋值的数据,从0开始赋值;
        int count = 0;
        //4x4,处理2个环形,4x5,也处理2个环形,中间列在while外边特殊处理;
        while (width >= (cycle + 1) * 2 && height >= (cycle + 1) * 2) {
            //赋值环形上边
            j = cycle;
            for (i = cycle; i < width - cycle; i++) {
                array[i][cycle] = count;
                count++;
            }
            //赋值环形右边
            i = width - cycle - 1;
            for (j = cycle + 1; j < height - cycle; j++) {
                array[i][j] = count;
                count++;
            }
            //赋值环形下边
            j = height - cycle - 1;
            for (i = width - 1 - cycle - 1; i >= cycle; i--) {
                array[i][j] = count;
                count++;
            }
            //赋值环形左边
            i = cycle;
            for (j = height-1 - cycle - 1; j > cycle; j--) {
                array[i][j] = count;
                count++;
            }
            cycle++;
        }

        //上面4x4可以满足,但是4x3或5x5无法满足对应逻辑,需要特殊处理;
        if ((cycle + 1) * 2 - width == 1 && width == height) {
            // 1x1,3x3场景;对中间数据进行赋值;
            array[cycle][cycle] = count;
        } else if ((cycle + 1) * 2 - width == 1) {
            // 3x5场景;处理中间一列的数据
            i = cycle;
            for (j = cycle; j < height - cycle; j++) {
                array[i][j] = count;
                count++;
            }
        } else if ((cycle + 1) * 2 - height == 1) {
            // 5x3场景;处理中间一行的数据;
            j = cycle;
            for (i = cycle; i < width - cycle; i++) {
                array[i][j] = count;
                count++;
            }
        }
    }
    // 打印二位数组
    void printArray(int[][] array, int width, int height) {
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {
                System.out.print(array[i][j] + "\t");
            }
            System.out.println();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值