LeetCode 59. Spiral Matrix II

LeetCode 59. Spiral Matrix II (螺旋矩阵 II)

题目

链接

https://leetcode-cn.com/problems/spiral-matrix-ii/

问题描述

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

示例

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

提示

1 <= n <= 20

思路

换汤不换药,只需要设置好边界值即可,注意不要陷入死循环。

复杂度分析

时间复杂度 O(n^2)
空间复杂度 O(n^2)

代码

Java

  public static int[][] generateMatrix(int n) {
        int up = 0;
        int down = n - 1;
        int left = 0;
        int right = n - 1;
        int[][] ans = new int[n][n];
        int x = 0;
        int y = -1;
        int turn = 0;
        int tag = 0;
        for (int i = 1; i <= n * n && tag != 4; i++) {
            if (turn == 0) {
                if (y < right ) {
                    y++;
                    ans[x][y] = i;
                    tag = 0;
                } else {
                    up++;
                    i--;
                    turn = 1;
                    tag++;
                }
            } else if (turn == 1) {
                if (x < down ) {
                    x++;
                    ans[x][y] = i;
                    tag = 0;
                } else {
                    right--;
                    i--;
                    turn = 2;
                    tag++;
                }
            } else if (turn == 2) {
                if (y > left ) {
                    y--;
                    ans[x][y] = i;
                    tag = 0;
                } else {
                    down--;
                    i--;
                    turn = 3;
                    tag++;
                }
            } else {
                if (x > up ) {
                    x--;
                    ans[x][y] = i;
                    tag = 0;
                } else {
                    left++;
                    i--;
                    turn = 0;
                    tag++;
                }
            }
        }
        return ans;
    }
posted @ 2022-04-28 21:34  cheng102e  阅读(13)  评论(0编辑  收藏  举报