蛇形矩阵(java实现)

蛇形矩阵:
一个呈螺旋状的矩阵,如图所示:
在这里插入图片描述
数字从第一行开始,向右变大,向下变大,向左变大,向上变大。
即解决此问题,首先我们知道它有四个方向,每次都是在这四个方向上进行操作:
Right, Down, Left, Up
此题需创建一个二维数组,行记为row,列记为col.
每次根据方向不同,对行和列进行不同的操作。因为它的顺序为右,下,左,上,因此还需要一个方法来判断它的下一个位置。

具体代码实现如下:

public class SnakePrint {
    public static int size = 0;
    private int value = -1;
    static int[][] array = null;
    enum Direction {
        Right, Down, Left, Up     //有4个方向,右->下->左->上
    }
    private Direction direction = null;
    //该方法用来判断下一个位置
    private Direction detectDirection(int row, int col) {
        Direction direction1 = this.direction;
        switch (direction1) {
            case Right:
                if ((col == size - 1) || (array[row][col + 1] != 0)) {
                    direction1 = Direction.Down;
                }
                break;
            case Down:
                if ((row == size - 1) || (array[row + 1][col] != 0)) {
                    direction1 = Direction.Left;
                }
                break;
            case Left:
                if ((col == 0) || (array[row][col - 1] != 0)) {
                    direction1 = Direction.Up;
                }
                break;
            case Up:
                if (array[row - 1][col] != 0) {
                    direction1 = Direction.Right;
                }
                break;
        }
        return direction1;
    }
    public void ArrayCount() {     //计算数组
        int row = 0, col = 0;
        for (int i = 0; i < size * size; i++) {
            array[row][col] = value;
            direction = detectDirection(row, col);
            switch (direction) {
                case Right:
                    col++;
                    break;
                case Down:
                    row++;
                    break;
                case Left:
                    col--;
                    break;
                case Up:
                    row--;
                    break;
                default:
                    return ;
            }
            value++;
        }
    }

    public SnakePrint(int size) {
        if (size <= 0) {
            return;
        }
        this.size = size;
        this.array = new int[size][size];
        this.value = 1;
        direction = Direction.Right;
        ArrayCount();
    }
    public static void main(String[] args) {
        SnakePrint snakePrint=new SnakePrint(6);
        for(int i=0;i<size;i++){
            for(int j=0;j<size;j++){
                System.out.print(array[i][j]+" ");
            }
            System.out.println();
        }
    }
}
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值