螺旋二维数组

本文探讨了如何遍历和操作螺旋形排列的二维数组,从数组的外层到内层,依次按照顺时针或逆时针方向访问每个元素。这种数据结构在某些算法问题中常见,并且提供了一种独特的方法来存储和处理矩阵数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.bjsxt.luoxuan;

import java.util.Scanner;

public class LuoXuan{
    //检测边界与是否该方向下一个已赋值
    //返回方向
    public static int checkBounds(int direction, int height, int width, int[][] array){
        int len=array.length;

        if(direction==4){
            if(width == len-1 || array[width+1][height]!=0){
                direction=2;
            }
        }else if(direction == 2){
            if(height==0 || array[width][height-1]!=0){
                direction=3;
            }
        }else if(direction == 3){
            if(width==0 || array[width-1][height]!=0){
                direction=1;
            }
        }else if(direction == 1){
            if(height==len-1 || array[width][height+1]!=0){
                direction=4;
            }
        }

        return direction;

    }

    public static void setNum(int[][] array){
        int len=array.length;
        int num=1;

        int height=0;
        int width=0;
        int direction=1;   //1 向右  2向左  3向上 4向下

        for(int i=0;i<len*len;i++){
            if(i==0){
                array[width][height] = num;
                num++;
            }

            if(direction==1 ){
                height++;
            }else if(direction == 2){
                height--;
            }else if(direction == 3){
                width--;
            }else if(direction == 4){
                width++;
            }

            direction=checkBounds(direction,height,width,array);

            //赋值
            array[width][height] = num;
            num++;

        }

    }

    public static void main(String[] args) {

        System.out.println("请输入数组的宽度");
        Scanner scanner = new Scanner(System.in); 
        int len=scanner.nextInt();
        int[][] array=new int[len][len];

        setNum(array);

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j]+"\t");
            }
            System.out.println();
        }

    }
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值