leetcode 螺旋矩阵 II Java

题干

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

想法

思路和螺旋矩阵相同,要点就是方向和边界

Java代码

public class GenerateMatrix {
    public int[][] generateMatrix(int n) {
        int x = 0;
        int y = 0;
        boolean[][] flag = new boolean[n][n];
        int[][] res = new int[n][n];
        //0123 右下左上
        int direct = 0;
        int trm = 1;
        while (x >= 0 && y >= 0 && x < n && y < n) {
            if (flag[x][y]) {
                break;
            }
            res[x][y] = trm;
            trm++;
            flag[x][y] = true;
            switch (direct) {
                case 0:
                    if (y == n - 1 || flag[x][y + 1]) {//走到右边界,注意有新的右边界
                        x++;//就向下走一步,并且改变方向
                        direct = 1;
                    } else {
                        y++;
                    }
                    break;


                case 1:
                    if (x == n - 1 || flag[x + 1][y]) {//走到下边界注意有新的下边界
                        y--;
                        direct = 2;
                    } else {
                        x++;
                    }
                    break;


                case 2:
                    if (y == 0 || flag[x][y - 1]) {//走到左边界注意有新的左边界
                        x--;//向上走
                        direct = 3;
                    } else {
                        y--;
                    }
                    break;

                case 3:
                    if (x == 0 || flag[x - 1][y]) {
                        y++; //如果向上走到头就右走
                        direct = 0;
                    } else {
                        x--;
                    } //向上走
                    break;


            }
        }

        return res;
    }


    public static void main(String[] args) {
        GenerateMatrix generateMatrix = new GenerateMatrix();

        int[][] test = generateMatrix.generateMatrix(3);
        for (int i = 0; i < 3; i++) {
            System.out.print("\n");
            for (int j = 0; j < 3; j++) {
                System.out.print(test[i][j]);

            }
        }

    }


}

leetcode刷题代码已经上传到git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值