java二位数组螺旋回型输出

问题描述:
在二维数组中
[
  [1,  2,  3,  4,  5],
 [16,17,18,19,6],
  [15,24,25,20,7],
  [14,23,22,21,8],
  [13,12,11,10,9]
]
在此数据中输出的顺序为1,2,3,4,5……..25。写出的算法就是输出这样的数字。
编程思想:
1. 定义四个变量left、right、top、bottom四个分别记录左边最小值left、右边最大值right、顶部的最小值top、底部最大值bottom。
2. 输出一圈之后left、top都加1,right、bottom都减1。
3. 进行之后的内部圈的重复第一、二步骤,直到left>right && top>bottom时候结束循环

代码如下:

package cn.wzq.sword_finger_offer;

public class LuoXuanHuiXingArray {

    public int[][] array = {
            {1,  2,  3,  4,  5},
            {16, 17, 18, 19, 6},
            {15, 24, 25, 20, 7},
            {14, 23, 22, 21, 8},
            {13, 12, 11, 10, 9}
    };

    public void display(int[][] array) {

        int left = 0, right = array.length - 1, top = 0, bottom = array.length - 1;


        while (left <= right && top <= bottom) {

            // 1. 从Left到Right遍历
            for (int x = left; x <= right; x++) {
                println(array[top][x]);
            }
            top++;

            // 2. 从Top到Bottom遍历
            for (int y = top; y <= bottom; y++) {
                println(array[y][right]);
            }
            right--;

            // 3. 从Right到Left遍历
            for (int x = right; x >= left; x--) {
                println(array[bottom][x]);
            }
            bottom--;

            // 4. 从Bottom到Top遍历
            for (int y = bottom; y >= top; y--) {
                println(array[y][left]);
            }
            left++;
        }

    }

    public void println(Object object){
        System.out.println(object);
    }

    public static void main(String[] arg){
        LuoXuanHuiXingArray L = new LuoXuanHuiXingArray();
        L.display(L.array);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值