LeetCode-100题(Hot) 59. 螺旋矩阵 II [Java实现] [极速]

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

示例 1:

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


思路其实和我写的 54.螺旋矩阵 是一致的,到了临界点转向就行了,因此直接贴代码和结果:

    public static final int RIGHT = 1;
    public static final int DOWN = 2;
    public static final int LEFT = 3;
    public static final int UP = 4;
    private int[][] result;

    public int[][] generateMatrix(int n) {
        this.result = new int[n][n];
        recursion(0, 0, 1, RIGHT, n, n*n, result);
        return result;
    }

    private static void recursion(int x, int y, int index, int direction, int width, int sum, int[][] result) {
        if (index == sum+1) return;
        result[x][y] = index;
        switch (direction) {
            case RIGHT:
                if (y+1 == width || result[x][y+1] != 0) {
                    direction = DOWN;
                    ++ x;
                } else {
                    ++ y;
                }
                break;
            case DOWN:
                if (x+1 == width || result[x+1][y] != 0) {
                    direction = LEFT;
                    -- y;
                } else {
                    ++ x;
                }
                break;
            case LEFT:
                if (y-1 == -1 || result[x][y-1] != 0) {
                    direction = UP;
                    -- x;
                } else {
                    -- y;
                }
                break;
            case UP:
                if (x-1 == -1 || result[x-1][y] != 0) {
                    direction = RIGHT;
                    ++ y;
                } else {
                    -- x;
                }
                break;
        }
        recursion(x, y, index+1, direction, width, sum, result);
    }

                

 时间复杂度 O(N) 额外空间复杂度 O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值